我已经用webpack生成了bundle.js,但是我的React App继续使用/static/bundle.js

时间:2019-12-20 10:09:03

标签: javascript reactjs webpack bundle webpack-4

我正在/ dist文件夹中生成.js和.js.gz,但实际上我需要此文件位于/ build / static / js中

当我将我的react应用上传到生产环境时,我上传到服务器的唯一文件是build文件夹,因此不会考虑webpack生成的文件。

这是在运行(/ static / js /)时使用我的应用程序的.js文件,而不是生成的Webpack。

enter image description here

您知道我如何强制Webpack在/ build文件夹中创建.js和.js.gz文件吗?

这是我的webpack.config.js:

var path = require('path');
const CompressionPlugin = require('compression-webpack-plugin');

module.exports = {
  mode: 'production',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },
      {
      test: /\.svg$/,
      loader: 'svg-inline-loader'
      }
    ]
  },
  plugins: [
     new CompressionPlugin({
     algorithm: 'gzip',
     test: /\.js$|\.css$|\.html$/,
     threshold: 10240,
     minRatio: 0.8
     })
    ]

}

这是package.json中的脚本部分

  "scripts": {
    "analyze": "source-map-explorer 'build/static/js/*.js'",
    "start": "react-scripts start",
    "dev": "webpack --mode development",
    "build": "webpack --mode production",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

2 个答案:

答案 0 :(得分:0)

您捆绑的文件将转到 output 变量提及的路径。

将此行从以下位置更改:path:path.resolve(__ dirname,'dist') 到:path:path.resolve(__ dirname,'build / static / js')

答案 1 :(得分:0)

我已经看到,如果您同时拥有该文件的两个版本:

main.js main.js.gz

浏览器按gzip版本询问,服务器仅发送一个gzip,但是您必须具有两个版本!

谢谢!