optimize webpack in javascript

There are several ways to optimize webpack for performance:

  1. Minimize and compress your JavaScript code using plugins like UglifyJSPlugin or TerserPlugin.
index.tsx
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
  optimization: {
    minimizer: [new UglifyJSPlugin(), new TerserPlugin()]
  }
};
217 chars
9 lines
  1. Use the SplitChunksPlugin to split your code into smaller chunks and load only what is needed.
index.tsx
module.exports = {
  optimization: {
    splitChunks: {
      chunks: 'all'
    }
  }
};
89 chars
8 lines
  1. Use the DefinePlugin to define environment variables and remove unused code at compile time.
index.tsx
const webpack = require('webpack');

module.exports = {
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    })
  ]
};
173 chars
10 lines
  1. Load only the required modules using dynamic imports instead of importing everything up front.
index.tsx
import('lodash').then(_ => {
  // Use Lodash here
});
54 chars
4 lines
  1. Use a caching mechanism like webpack's caching or service worker caching to speed up subsequent page loads.
index.tsx
module.exports = {
  output: {
    filename: '[name].[chunkhash].js'
  },
  plugins: [
    new webpack.HashedModuleIdsPlugin(),
    new webpack.optimize.ModuleConcatenationPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: ({ resource }) => (
        resource &&
        resource.indexOf('node_modules') !== -1 &&
        resource.match(/\.js$/)
      ),
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      minChunks: Infinity,
    }),
  ],
  devtool: '#source-map',
};
624 chars
25 lines

gistlibby LogSnag