Webpack packs all of our files into a single JS file, so even if you’re a small project, the packed file will be very large. Here’s how to optimize in multiple ways.

Remove unnecessary plug-ins

When we first started using WebPack, the development environment and production environment used the same WebPack configuration file, resulting in the production environment packaged JS file containing a lot of unnecessary plug-ins. Such as HotModuleReplacementPlugin NoErrorsPlugin… No matter what optimization method is used at this time, it does not have much effect. So, if your package is too large, check to see if it includes these plug-ins.

Extracting third-party libraries

The core code of a react library is 627 KB, which would be a lot to pack with our source code. So you can set it up in webpack

{
  entry: {
   bundle: 'app'
    vendor: ['react']
  }

  plugins: {
    new webpack.optimize.CommonsChunkPlugin('vendor',  'vendor.js')
  }
}Copy the code

This packaging creates an additional vendor.js file, which we’ll import before we import our own code. For example, in index.html

 
 Copy the code

In addition to this approach, it is possible to introduce third-party libraries by referring to external files, such as the following configuration

{
  externals: {
     'react': 'React'
  }
}Copy the code

The externals key is used for require, such as require(‘react’), and the value of the externals object specifies how to access the object in global, in this case window.react. The index.html should look like this


Copy the code

Of course, I prefer the first method.

Code compression

Webpack comes with a compression plug-in called UglifyJsPlugin, which you just need to introduce in your configuration file.

{
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    })
  ]
}Copy the code

When this plug-in is added, compilation is significantly slower, so it is usually only enabled in production.

In addition, the server side can also enable gzip compression, the optimization effect is more obvious.

The code segment

What is code splitting? As we know, the general loading of a web page will load all the JS code down. But for a Web app, we’d rather have code that only loads the current UI, not the parts that aren’t clicked.

It seems like a lot of trouble, but it can be easily implemented through Webpack’s code split and react Router. For an example, see Huge Apps for the React Router. However, here is the previous configuration step on the pit.

Code split does not support ES6 module system, so be careful when importing and exporting, especially export. If you export a component using ES6, it will fail regardless of whether the import is CommomJs or AMD, and no error will be reported!

Of course, IT’s because I’m new to NodeJS, and I started with ES6 style. In addition to this, it is also important to note that publicPath is added to the WebPack configuration file in production

output: {
    path: xxx,
    publicPath: yyy,
    filename: 'bundle.js'
}Copy the code

Otherwise, the path will fail when Webpack loads chunk.

Set the cache

Before starting this section, take a look at one of God’s articles on how to develop and deploy front-end code in large companies.

For static files, if the contents of the file have not changed after the first fetch, the browser simply reads the cached file. What if the cache Settings are too long and the files need to be updated? Well, using MD5 as the file name of the file contents is a good solution. How do you do that with Webpack

output: {
    path: xxx,
    publicPath: yyy,
    filename: '[name]-[chunkhash:6].js'
}Copy the code

The hash value is added to the packed file name

const bundler = webpack(config)

bundler.run((err, stats) => {
  let assets = stats.toJson().assets
  let name

  for (let i = 0; i < assets.length; i++) {
    if (assets[i].name.startsWith('main')) {
      name = assets[i].name
      break
    }
  }

  fs.stat(config.buildTemplatePath, (err, stats) => {
    if (err) {
      fs.mkdirSync(config.buildTemplatePath)
    }

    writeTemplate(name)
  })
})Copy the code

Manually call webPack’s API, get the packaged file name, and update the HTML code with writeTemplate. Full code jabber gitst.

This way, we can make the file cache very long without worrying about updates.