using gzip compression with webpack and express, s

2019-09-02 05:28发布

I've just installed and setup gzip compression to my webpack and express files. The plugins snippet of my webpack.config.js now looks like this:

plugins: [
    new webpack.DefinePlugin({ // <-- key to reducing React's size
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    }),
    new webpack.optimize.UglifyJsPlugin(), //minify everything
    new webpack.optimize.AggressiveMergingPlugin(),//Merge chunks
    new CompressionPlugin({
      asset: "[path].gz[query]",
      algorithm: "gzip",
      test: /\.js$|\.css$|\.html$/,
      threshold: 10240,
      minRatio: 0.8
    }),
    HTMLWebpackPluginConfig,
    new Dotenv({
      path: './.env', // Path to .env file (this is the default)
      systemvars: true //
    })]
};

and a snippet from my server.js file now looks like this:

// Use our router configuration when we call /
if (process.env.NODE_ENV === 'production') {
  app.use(express.static('dist'), router);
  app.get('/*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
  });
  app.get('/*.js', (req, res) => {
    req.url = req.url + '.gz';
    res.set('Content-Encoding', 'gzip');
  });
} else {
  app.use('/', router);
}

When I deploy the app to production I can see the code that has actually built two files, the index_bundle.js and the index_bundle.js.gz here:

remote:        index_bundle.js    1.49 MB       0  [emitted]  [big]  main
remote:        index_bundle.js.gz     375 kB          [emitted]  [big]
remote:        index.html    3.88 kB          [emitted]

The compression is successful, however, when I test my website using the chrome console it is still serving the index_bundle.js file through the network rather than the new compressed file:

index_bundle.js being server rather than index_bundle.js.gz

Any ideas on potentially why this is happening?

0条回答
登录 后发表回答