The technical stack of the project is DVA + ANTD-Mobile. Since it is an early project, the webpack version in the project is 3.5.6, so I will add the writing method of webpack 4.x version to some configurations. Some plugins or related configurations are listed less or explained relatively simple, you can go to webpack official website or the corresponding plugin Github to view the detailed parameter configuration. Have inadequacy place also please correct 馃檹.

Roadhog is a command line utility that includes dev, build, and test. It is based on react-dev-utils, which is consistent with the creation-react-app experience. You can imagine it as a configurable version of create-React-app.

Roadhog has some specific parameters to write the relevant packaging configuration, see Roadhog for details.

However, to add some configurations that Roadhog does not provide, such as the package analysis plugin webpack-bundle-Analyzer, you need to create a separate webpack.config.js file to do the configuration. (did not find a direct configuration in.webpackrc.js file method, there is a solution to the dude also please inform 馃憖)

Optimization takes place in the following directions:

  • First add the package analyser-Analyzer
  • Reduce the size of packed files
  • Improve packing speed
  • Improves the loading speed of packaged files
  • Processing for some larger modules
  • CDN introduces some underlying dependencies

Package analysis – webpack-bundle-Analyzer

This plugin analyzes the size of each module file after the project is packaged

npm i -D webpack-bundle-analyzer

For details about the parameters, see Configuration details and Parameter links

/* webpack.config.js */
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; 路 plugin: [路路 New BundleAnalyzerPlugin()] 路路Copy the code
/ * package. Json * /..."scripts": {..."analyz": "NODE_ENV=production npm_config_report=true npm run build"},...Copy the code

Run: NPM run analyz, default address http://127.0.0.1:8888/

Analyz analyzes some pages

Overall reduction in packing volume

UglifyJsPlugin

Remove comments and console from files, remove redundant code, and reduce packaging size. You can also delete the debugger and set the cache.

Webpack 3 x version: through webpack. Optimize. UglifyJsPlugin Settings

/ * webpack. Config. Js * /... the plugins: [... new webpack. Optimize. UglifyJsPlugin ({cache:true,
      compress: {
        warnings: false, // Whether to output a warning message when UglifyJS deletes code that is not usedfalse
        drop_debugger: true// Automatically delete debugger drop_console:true, // Automatically delete console.log},}), 路路路]Copy the code

Webpack 4.x version: Webpack 4 x version removed webpack. Optimize. The use of UglifyJsPlugin, through configuration optimization, minimize and optimization. The minimizer customize compression related operations.

npm i -D uglifyjs-webpack-plugin

/* webpack.config.js */

路路路
const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); Module. exports = {optimization: {minimizer: [new UglifyJsPlugin({// config})],},};Copy the code

Improve packing speed

ParalleUglifyPlugin

Improve the compression speed of JS during compilation and packaging. You can also set the removal of comments and console code during packaging. You can merge UglifyJsPlugin mentioned above

npm i -D webpack-parallel-uglify-plugin

/* webpack.config.js */

const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin');
plugin: [
	路路路
  new ParallelUglifyPlugin({
    cacheDir: '.cache/', // Used as an optional absolute path for the cache. If not provided, caching is not used. uglifyJS: { output: { comments:false// Whether to keep comments in code. Defaults to keep}, warnings:false, // Whether to output a warning message when UglifyJS deletes code that is not usedfalse
      compress: {
        drop_console: true, // Whether to delete all console statements in the codefalse
        collapse_vars: true, // Whether to embed a variable that is defined but used only once, the default valuefalse
        reduce_vars: true// Whether to extract static values that occur more than once but are not defined as variables to referencefalse},},}), 路路路Copy the code

happypack

Enable multi-process editing to improve the loader resolution speed

npm i -D happypack

/* webpack.config.js */

const HappyPack = require('happypack');
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });
const createHappyPlugin = (id, loaders) =>
new HappyPack({
  id: id,
  loaders: loaders,
  threadPool: happyThreadPool,
  verbose: process.env.HAPPY_VERBOSE === '1', // make happy more verbose with HAPPY_VERBOSE=1 }); The plugin: [the createHappyPlugin (...'happy-babel', [
    {
        loader: 'babel-loader',
        options: {
          babelrc: true,
          cacheDirectory: true},},]) 路路路]Copy the code

Increase loading speed

Compress the packed file

Reduce the file volume, save the server network bandwidth, speed up the website opening speed. After server compression, client browser fast compression principle, can greatly reduce the traffic of the site.

There are two compression methods: ZIP compression and GZIP compression.

  • Zip – webpack-plugin-zip: zip all files into a zip file

    npm i -D zip-webpack-plugin

/* webpack.config.js */

const ZipPlugin = require('zip-webpack-plugin'); ... the new ZipPlugin ({filename:'index.zip',...})Copy the code

Zip file snapshot

  • Compression -webpack-plugin – gzip compression, compress each file individually

    npm i -D compression-webpack-plugin

/* webpack.config.js */

const CompressionPlugin = require('compression-webpack-plugin'); ... the new CompressionPlugin ({filename:'[path].gz[query]',
  algorithm: 'gzip'.test: / \. Js $| \. CSS $/, threshold: 10240, minRatio: 0.8,}),...Copy the code

A screenshot of a gzip compressed file

CommonChunkPlugin – Code split packaging

The class library dependent on the import file is extracted and packaged into the Vendor file, which is stored in the cache after the first loading. The subsequent loading will be read in the browser cache to improve the loading speed.

Webpack 3. X version

/ * webpack. Config. * /... / js/wrap up all the dependent libraries to the vendor file new webpack.optimize.Com monsChunkPlugin ({name:'vendor',
  minChunks: function (module) {
    return (
      module.resource &&
      /\.js$/.test(module.resource) &&
      module.resource.indexOf(path.join(__dirname, './node_modules')) = = = 0); }})...Copy the code

4 webpack x version

/* webpack.config.js */ * optimization: {splitChunks: {chunks:'all'MinSize: 30000, // import minChunks only if the imported component or file is larger than 300000 bytes = 30KB: // import chunks only if the imported component or file is larger than 300000 bytes = 30KB: 1, // How many times a module is used does the code split...}}Copy the code

The CSS removes the JS file and packages it separately

npm i -D extract-text-webpack-plugin

/* webpack.config.js */

const ExtractTextPlugin = require('extract-text-webpack-plugin'); 路路 plugins: [new ExtractTextPlugin('[name].[contenthash].css'...)]Copy the code

Handling of large files

From analyz analysis, it can be seen that the files of moment, core-js and crypto-js are too large. The following three modules are processed.

Moment – There are two ways to fix the moment file size

  • IgnorePluginThe plug-in
/* webpack.config.js */ plugins: [路路路 路 // Ignore all local files in moment.js new webpack.ignoreplugin (/^\.\/locale$/, /moment$/), 路路路]Copy the code

To manually import the locale file:


const moment = require('moment');
require('moment/locale/ja');

moment.locale('ja'); .Copy the code
  • ContextReplacementPluginThe plug-in
/* webpack.config.js */ plugin: [... / / only load ` moment/locale/ja. Js ` and ` moment/locale/it js ` new webpack. ContextReplacementPlugin (/ moment [/ \ \] locale $/, / ja | it /...)Copy the code

You do not need to manually import locale files

const moment = require('moment'); // Don't need moment.locale('ja'); .Copy the code

core-js

I didn’t use core-js in my project. The search plugin learned that this was the library used by @babel-Polyfill, and it was packaged with it. Extract babel-Polyfill and introduce CDN into polyfill

/* webpack.config.js */
路路路
externals: {
  'babel-polyfill': 'window'} 路路路 路 /* index.html script introduces */ <script SRC ="https://cdn.bootcss.com/babel-polyfill/6.22.0/polyfill.min.js"></script>
Copy the code

crypto-js

This is the encryption and decryption related library

The crypto-js method was referenced directly in the node_modules file, which added a lot of useless methods to the package:

const CryptoJS = require('crypto-js'); // The method calls cryptojs.hmacsha256 cryptojs.enc.base64 cryptojs.enc.utf8Copy the code

Optimize the use of related methods, which use directly into the crypto-js file of the method:

const CryptoJS_HmacSHA256 = require('crypto-js/hmac-sha256');
const CryptoJS_Base64 = require('crypto-js/enc-base64');
const CryptoJS_Utf8 = require('crypto-js/enc-utf8');
Copy the code

CDN introduces base dependencies

Extract React and ReactDom, CDN introduced

/* webpack.config.js */
路路路
externals: {
  'react': 'React'.'react-dom': 'ReactDOM'} 路路路 路 /* index.html script introduces */ <script SRC ="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
Copy the code

END

Old project optimization is not easy, sort out the optimization method, record.

In fact, the react-count-animation module file is quite large, but there is no optimization solution, please inform us 馃檹.