Webpack simple configuration and its usage two

One, write a maintainable webpack build configuration

Chestnut: Build a configuration package design

The significance of separating the build configuration into an npm package

Passability : business developers do not need to pay attention to build configuration; unified team build scripts

Maintainability : reasonable split of build configuration; reademe, changelog document

Quality : smoke test, unit test, test coverage; continuous inheritance

 

Build options for configuration management

1) Through multiple configuration files to manage the construction of different environments, the webpack --config parameter controls the configuration files used, such as

Basic configuration: webpack.base.js; development environment: webpack.dev.js; production environment: webpack.prod.js; ssr environment: webpack.ssr.js

2) Design the build configuration as a library, such as hjs-webpack Neutrino webpack-blocks

Specification: git commit log, README, ESLINT specification, Semver specification

Quality: Smoke test, unit test, test coverage and CI

3) Draw a tool for management, such as: create-react-app kyt nwb

4) Write all the configuration in a file, control the branch selection through the --env parameter,

1) 2) Suitable for small teams, large teams can choose 3) Method

 

Configuration via webpack-merge combination

const merge = require("webpack-merge)
merge(
    {a:[1], b:5, c:20},
    {a:[2], b:6, d:35}
)
>{a:[1,2],b:6,c:20,d:35} // 非对象或非数组,则有相同的变量名,后面的覆盖前面的
合并配置:module.exports=merge(baseConfig,devConfig)

 

Two, webpack construction speed and volume optimization strategy

Volume optimization method:

1)scope hoisting

2)tree-shaking

3) Separation of public resources

4) Image compression

5) Dynamic polyfill

 

Ways to improve the speed of construction:

1) Make full use of the cache to increase the speed of the second build

2) Further subcontracting: pre-compiled resource modules

 

Chestnut: construction speed and speed analysis

1) Use webpack's built-in stats: built statistics

 

2) Speed ​​analysis: use speed-measure-webpack-plugin to analyze the time consumption of the entire package, the time consumption of each plug-in and loader

Install plugin

npm install -D speed-measure-webpack-plugin

Create an object

const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");

const smp = new SpeedMeasurePlugin();

Wrap the contents of the previous module.exports in smp.wrap()

smp.wrap(...)

 

3) Volume analysis: use webpack-bundle-analyzer

You can analyze the file size of the dependent third-party module and the code size of the component in the business

Installation dependencies

npm install -D webpack-bundle-analyzer

Configuration

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  plugins: [
    new BundleAnalyzerPlugin()
  ]
}

 

Chestnut: Use the higher version of webpack and node

 

Chestnut: Make full use of the cache to increase the speed of the second build-the speed of the first build will not change, and the speed of the next build will change

Caching ideas:

1) Babel-loader turns on caching to parse js grammar or jsx grammar. When parsing the same grammar next time, you can read the cached content to improve the speed of parsing

2) terser-webpack-plugin enables caching to improve the compression speed when the code is compressed

3) Cache-loader or hard-source-webpack-plugin to improve the speed of the module conversion phase

If caching is turned on at the code level, there is a .cache directory under node_modules. For example, when babel-loader is turned on, the folder babel-loader (node_modules/.cache/babel-loader/....) will be generated. It contains the parsed js file

Note : If the cache is turned on, it may affect the update of the package. For example, the package [email protected] is installed in the project, and then updated to [email protected], but it is found that the code of this package is still the previous version

Solution: Remove the .cache folder as a whole before updating the package.

 

Take hard-source-webpack-plugin as a chestnut:

1) Install hard-source-webpack-plugin

npm install -D hard-source-webpack-plugin

2) In the configuration file, import the plug-in and configure it

const HardSourceWebpackPlugin = require('hard-source-webpack-plugin')



plugin: [
  new HardSourceWebpackPlugin()
]

Chestnut: narrowing the build target

Purpose: as few building blocks as possible,

For example: babel-loader does not resolve node_modules

module.exports = {
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: ''babel-loader,
                exclude: 'node_modules
            }
        ]
    }
}

For example: reduce the scope of file search:

Webpack is very similar to the way that node finds files. Specify the path or file type to be searched to reduce the search time

Optimize resolve.modules configuration (reduce module search level)

Optimize resolve.mainFields configuration

Optimize resolve.extensions configuration

Reasonable use of alias

resolve: {
    alias: {
        react: path.resolve(__dirname, ./node_modules/react/dist/react.min.js') // 直接给定取别名的路径
    },
    modules: [path.resolve(__dirname, 'node_modules')], // 安装第三方包是在node_modules目录下,那么在引进第三方包的时候直接到node_module目录下查找
    extensions: ['.js'], // 指定查找文件的类型
    mainFields: ['main']   // 发布到npm上的包会指定入口路径,即main字段的值,即查找文件只在该路径下查找
}

 

Chestnut: tree shaking (tree shaking optimization)

Concept: A module may have multiple methods. As long as one of the methods is used, the entire file will be packaged into the bundle, while tree shaking just packs the used methods into the bundle, and the unused methods will be in the bundle. Erase the uglify stage

Use: webpack supports by default, just set modules: false in .babelrc, note: it is enabled by default in mode: production

Requirements: must be ES6 syntax, cjs method does not support

How to delete useless css?

PurifyCSS: Traverse the code and identify the css class that has been used

uncss: HTML needs to be loaded through jsdom, all styles are parsed through PostCSS, and document.querySelector is used to identify selectors that do not exist in the html file

How to use PurifyCSS in webpack

Use purgecss-webpack-plugin and min-css-extract-plugin together

1) Install the plugin purgecss-webpack-plugin

npm i purgecss-webpack-plugin -D

2) Introduce plug-ins in the project

The following is a single file entry, reference address: https://www.npmjs.com/package/purgecss-webpack-plugin

const PurgeCSSPlugin = require('purgecss-webpack-plugin')

const PATHS = {
  src: path.join(__dirname, 'src')
}




 plugins: [
    new PurgeCSSPlugin({
      paths: glob.sync(`${PATHS.src}/**/*`,  { nodir: true }),
    })
 ]

Chestnuts: image compression

Requirements: imagemin or tinypng API based on Node library

Use: configure image-webpack-loader

Use reference document: https://www.npmjs.com/package/image-webpack-loader

1) Install the plug-in

npm install image-webpack-loader -D

2) Set in the configuration file

module.exports.module.rules = [{
                test: /\.(png|jpg|jpeg|gif|svg)$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: 'img_[name][hash:8].[ext]'
                        }
                    },
                    {
                        loader: 'image-webpack-loader',
                        options: {
                          mozjpeg: {
                            progressive: true,
                          },
                          // optipng.enabled: false will disable optipng
                          optipng: {
                            enabled: false,
                          },
                          pngquant: {
                            quality: [0.65, 0.90],
                            speed: 4
                          },
                          gifsicle: {
                            interlaced: false,
                          },
                          // the webp option will enable WEBP
                          webp: {
                            quality: 75
                          }
                        }
                    }
                ]
            }]

Chestnut: build volume optimization, dynamic polyfill

Use polyfill-service: only return the polyfill that the user needs, ua identification, and issue different polyfills

 

Three, through the source code, master the principle of webpack packaging

Chestnut: analysis of webpack startup process

What happened when the project started?

Generally, to start a project, we will hit the console and enter npm run dev and other statements, and then the project will start, or enter webpack entry.js and bundle.js in the console to run directly--------What happens in this process? ? ?

When the above statement is executed, npm will let the command line tool enter the node_modules/.bin directory to find whether there is a webpack.sh webpack.cmd file, and execute it if it exists, otherwise an error will be thrown; the actual entry file path: node_modules/webpack/bin/ webpack.js ( the command is defined here, but is it the command provided by the webpack package or the webpack-cli package? )

Globally installed packages will be searched under userLocal/.bin, but we generally install webpack locally, that is, installed into specific projects, so we will look for files from node_modules/.bin in the root directory of the project.

When installing a package locally, if you want to have this command in the .bin directory, you must specify it in the bin field of package.json

 

Look at what is defined in the node_modules/.bin/webpack file

process.exitCode = 0  // 正常执行返回
const runCommand = (command, args) => {}      // 运行某个命令
const isInstalled = packageName => {}     // 判断某个包是否安装了
const CLIs = [....]  // webpack可以用的cli:webpack-cli    webpack-command
const isntalledClis = CLIs.filter(cli => cli.installed)   // 判断安装了那些cli
if (isntalledClis.length === 0) {// 根据安装数量进行处理
} else if (isntalledClis.length === 1) {
} else {
}

Result after startup:

webpack finally finds the npm package webpack-cli (webpack-command) and executes cli

 

Chestnut: webpack-cli source code reading

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/tangxiujiang/article/details/111773610