Реакция сборки продукта показывает пустую страницу - PullRequest
0 голосов
/ 21 февраля 2020

У меня есть проблема, когда моя рабочая сборка показывает пустую страницу при обслуживании с простым сервером узлов. Я пытался решить эту проблему по-разному, но не могу найти решение этой проблемы. Любые предложения, как решить эту проблему, будут высоко оценены. Я использую BrowserRouter в качестве опции маршрутизации на стороне клиента.

Вот мой webpack.common. js код для производственной сборки:

const path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");

const outputPath = path.join(__dirname, "dist");
const port = process.env.PORT || 8000;

module.exports = {
  context: __dirname,
  entry: {
    main: ["@babel/polyfill", "./src/App.js"]
  },
  output: {
    path: path.join(__dirname, "dist"),
    filename: "bundle.js"
  },
  resolve: {
    modules: ["node_modules", "./src"],
    extensions: [".js", ".jsx"]
  },
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          use: "css-loader!sass-loader"
        })
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          use: "css-loader"
        })
      },
      {
        test: /\.(js|jsx)$/,
        loader: "babel-loader",
        exclude: /node_modules/
      },
      {
        test: /\.(jpg|jpeg|png|gif|mp3|svg)$/,
        loaders: ["file-loader"]
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader"
          }
        ]
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("bundle.css"),
    new HtmlWebpackPlugin({
      baseUrl: process.env.NODE_ENV == 'development' ? '/' : '/',
      filename: "index.html",
      template: path.join(__dirname, "./public/index.html")
    })
  ],
  devServer: {
    port,
    historyApiFallback: true,
    publicPath: "/"
  }
};

Вот запись для компилятора для запуска производственной сборки:

const webpack = require('webpack');
const merge = require('webpack-merge');

const webpackCommonConfig = require('./webpack.config.common');

module.exports = merge(webpackCommonConfig, {
    plugins: [
        new webpack.EnvironmentPlugin({ NODE_ENV: 'production' }),
    ],
    devtool: "source-map",
    devServer: {
        compress: true,
    },
});

Вот код сервера узлов, обслуживающего приложение:

const express = require('express')
const path = require('path')
const port = process.env.PORT || 8000
const fs = require('fs');
const app = express()


app.get(['/bundle.css', '/bundle.css.map'], (req, res) => {
    res.writeHead(200, {'Content-Type': 'text/css'});
    fs.createReadStream(path.resolve(__dirname, `../dist/${req.url}`)).pipe(res);
})

app.get(['/bundle.js', '/bundle.js.map'], (req, res) => {
    res.writeHead(200, {'Content-Type': 'text/javascript'});
    fs.createReadStream(path.resolve(__dirname, `../dist/${req.url}`)).pipe(res);
})
app.get('*', function (request, response){
  response.sendFile(path.resolve(__dirname, '../dist', 'index.html'))
})

app.listen(port)
console.log("server started on port " + port)

Вот индекс. html, который скомпилирован в папку dist:

<!DOCTYPE html>
<html lang="en" style="height:100%">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.gif">
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    <title>Zoi</title>
  <link href="bundle.css" rel="stylesheet"></head>
  <body style="height:100%">
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
  <script type="text/javascript" src="bundle.js"></script></body>
</html>
...