preface

For the H5 project build configuration in the Build section, readers who have not read the previous series can preview the entire series by pulling down to the series directory below

Although the optimized configuration of Webpack has been mentioned in the blog, it will be added to the whole series

Webpack

Auxiliary analysis plug-in

speed-measure-webpack-plugin

Using this plug-in, you can calculate the running time of loader and plugin during the editing process, and see the cause of the slow construction speed of a certain environment

const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
 
const smp = new SpeedMeasurePlugin();
 
const webpackConfig = {
  plugins: [
    new MyPlugin(),
    new MyOtherPlugin()
  ]
}
module.exports = smp.wrap(webpackConfig);
Copy the code

webpack-bundle-analyzer

Using this plug-in, you can export HTML and analyze the volume of the bundle that is exported after it is packaged

new BundleAnalyzerPlugin({
  // Can be 'server', 'static' or 'disabled'.
  // In 'server' mode, the analyzer will start the HTTP server to display the package report.
  // In "static" mode, a single HTML file with a report is generated.
  // In 'disabled' mode, you can use this plugin to set 'generateStatsFile' to 'true' to generate Webpack Stats JSON files.
  analyzerMode: 'server'.// Start the HTTP server on the host used in server mode.
  analyzerHost: '127.0.0.1'.// The HTTP server will be started on the port used in server mode.
  analyzerPort: 8888.// Path binding, which will generate the report file in 'static' mode.
  // Relative to the bundled output directory.
  reportFilename: 'report.html'.// The module size is displayed in the report by default.
  // It should be either 'stat', 'parsed' or 'gzip'.
  // For more information, see the "Definitions" section.
  defaultSizes: 'parsed'.// Automatically opens the report in the default browser
  openAnalyzer: true.// If true, the Webpack Stats JSON file will be generated in the bundle output directory
  generateStatsFile: false.// If 'generateStatsFile' is' true ', the Webpack Stats JSON file name will be generated.
  // Relative to the bundled output directory.
  statsFilename: 'stats.json'.// stats.tojson () option.
  // For example, you can exclude the source of modules in the statistics file using the 'source: false' option.
  / / here to view more options: HTTPS: / / github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
  statsOptions: null.logLevel: 'info' // Log level. It can be 'message', 'warning', 'error' or 'silence'.
})
Copy the code

This configuration is basic also very few people to change, literally put out to see

As shown in the figure, what are the files contained in the package, what is the size ratio, module inclusion relationship, dependencies, whether the files are repeated, and what is the size after compression? We can further optimize according to the above figure

The optimization process

Cache configuration

Babel – loader cache

{
  test: /\.(js|mjs|jsx|ts|tsx)$/,
  include: paths.appSrc,
  loader: require.resolve("babel-loader"),
  options: {
    customize: require.resolve(
      "babel-preset-react-app/webpack-overrides"
    ),
    plugins: [[require.resolve("babel-plugin-named-asset-import"),
        {
          loaderMap: {
            svg: {
              ReactComponent:
                "@svgr/webpack? -svgo,+titleProp,+ref! [path]"},},},], ["lodash"]],cacheDirectory: true.cacheCompression: false.compact: isEnvProduction,
  },
}
Copy the code

Terser webpack – plugin cache

new TerserPlugin({
  terserOptions: {
    parse: {
      ecma: 8,},compress: {
      ecma: 5.warnings: false.drop_console: true.comparisons: false.inline: 2,},mangle: {
      safari10: true,},keep_classnames: isEnvProductionProfile,
    keep_fnames: isEnvProductionProfile,
    output: {
      ecma: 5.comments: false.ascii_only: true,}},parallel: true.cache: true.sourceMap: shouldUseSourceMap,
})
Copy the code

It is mainly to add the cache configuration of loader and plugin in your project, and the effect is shown in the figure. When carefully comparing the construction speed of loader and plugin with cache enabled in the second build, there is a significant improvement

Increase the construction speed up to one times, delectable

Multi-core build

  • uglifyjs-webpack-plugin
  • happypack
  • thread-loader

These 3 use most, the net searches casually search a big, see officer oneself manual baidu, Google

Others have content, I will list, the actual effect is not ideal, even the configuration are too lazy to paste up

Resolution of the code

splitChunks: {
    chunks: 'initial'./ / used to hit the chunk, function module, the chunk () | RegExp | string
    cacheGroups: {
        common: {
            chunks: 'initial'.// all, async, initial, default async
            minChunks: 5.// Minimum number of shared modules
            name: 'common'./ / module name
            priority: 9./ / priority
            enforce: true // Ignore splitChunks
        },
        vendor: {
            test: /node_modules/,
            chunks: 'initial'.name: 'vendor'.priority: 10.enforce: true}}},Copy the code

This is the splitChunks code of Webpack4, one of which is to extract the public module reference and the other is to extract the third-party module reference

This gadget split to see their own needs, but the speed of construction is not much, the use of project optimization needs can try

CDN Configuration (Recommended & Not recommended)

externals: {
    moment: 'window.moment'.antd: 'window.antd'.lodash: 'window._'.react: 'window.React'.'react-dom': 'window.ReactDOM',}Copy the code

Use externals to extract the common code, place it in the CDN, and import it using script tags

Recommended reasons:

If your project can ensure the same domain name, only according to the gateway to distinguish projects, it is recommended to configure this configuration, after all, one project open, the rest of the project will be directly removed from the cache, improve the speed of subsequent projects open

Not recommended for:

  1. Need to deploy THEIR own CDN, the third party is not stable, hang up may need tea
  2. Project versions depend on references, upgrades can be problematic, and there are maintenance costs
  3. Inconsistent project versions, inconsistent references, increase the volume of a single project reference

The next article is a plug-in to solve this problem, in fact, our company uses quite hi, need to change the general point

hard-source-webpack-plugin

This add-on killer, introduced at the end, can be placed anywhere, providing an intermediate cache for modules.

const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
module.exports = {
  / /... plugins: [
    new HardSourceWebpackPlugin()  
]}
Copy the code

Attached is the timeline of the final project construction

Build speed went from 7s to 2.5s (mostly secondary builds, cache improvements, you name it).

The above configuration can be general, and actually used, lift effect is not big did not put up, without what meaning. I have built a complex project with hundreds of pages and only used 9s. If you are interested, you can try again.

Full series of blog entries

The backend module

  1. DevOps – Gitlab Api usage (completed, click to jump)
  2. The conversation – build enterprise foundation platform Basic platform building last | foundation platform structures, medium-length | foundation platform set up next
  3. Devops-jenkins pipelined construction
  4. DevOps – Gitlab CI pipeline construction
  5. Devops-docker use
  6. DevOps – Release task flow design
  7. DevOps – Code review points
  8. Devops-node monitors service quality

The front-end module

  1. DevOps – H5 base scaffolding
  2. Devops-react project development

The above series may be adjusted later based on the actual development progress of the DevOps project

The end of the

This project is from zero development, the subsequent series of blog will be launched according to the actual development progress (really f * * king tired), after the completion of the project, will open part of the source code for your reference.

Why open part of the source code, because some business needs to fit the actual project targeted development, open out of the public module I write seriously

In order to write a series of blog, actually really masturbate a complete system (not generally tired), feel good students trouble three even (praise, attention, forward).