The basic configuration

Split configuration and merge

Mode, entry, output, rules, plugins, etc

Start a local service

devServer

Processing ES6

babel-loader

Processing styles Loader execution order, from back to front

Style-loader, CSS-loader, and postCSs-loader

Processing images

Dev: file-loader uses the image URL directly

PRD: Consider the base64 encoding case

Images smaller than 5KB are generated in Base64 format. Otherwise, file-loader is used to generate URL format

modular

Advanced configuration

Multiple entry

1Entry Add multiple JS entry files2FileName of output is set to'[name].[contentHash:8].js'
3HtmlWebpackPlugin generates multiple HTMLCopy the code

Remove the CSS file

MinCssExtractPlugin. Replace style – loader loader

Rules configuration

/ / CSS to pull away
{
    test: /\.css$/,
    loader: [
        MinCssExtractPlugin.loader,
        'css-loader'.'postcss-loader']}/ / out of less
{
    test: /\.less$/,
    loader: [
        MinCssExtractPlugin.loader,
        'css-loader'
        'less-loader'.'postcss-loader']}Copy the code

Plugins configuration

// Remove the CSS file
new MiniCssExtractPlugin({
    filename: '/css/main.[contentHash:8].css'
})
Copy the code

Compress CSS

optimization: {
    / / compress CSS
    minimizer: [new TerserJSPlugin({}), new OptimizeCssAssetsPlugin()]
}
Copy the code

Pull out the common code

optimization: {
    / / compress CSS
    minimizer: [new TerserJSPlugin({}), new OptimizeCssAssetsPlugin()]
    // Split code blocks
    splitChunks: {
        chunks: 'all'./** initial rukou1 chunk: async chunk is not processed for an imported file, and all chunk is processed for an imported file

        // Cache grouping
        cacheGroups: {
            // Third party module
            vendor: {
                name: 'vendor'./ / the chunk name
                priority: 1.// The permission is higher
                test: /node_modules/,
                minSize: 0.// Size limit
                minChunks: 1 // At least several times
            },
            // Public module
            common: {
                name: 'common'.priority: 0.minSize: 0.minChunks: 2}}}}Copy the code

Lazy loading

Import () defines a chunk. Dynamic loading syntax is supported by default

JSX

@babel/preset-react

"presets": ["@babel/preset-react"]
Copy the code

Vue

vue-loader

Module Chunk Bundle

1,module- each source file, all modules in Webpack2, chunk-entry that is merged into multiple modulesimport() splitChunk
3Bundle - The final output fileCopy the code

Optimize packaged build efficiency (development experience and efficiency)

1. Optimize babel-Loader

{
    test: /\.js$/,
    use: ['babel-loader? cacheDirectory'].// Enable caching
    include: path.resolve(__dirname, 'src'), // Specify the scope
    // Include and exclude are optional
    // exclude: path.resolve(__dirname, 'node_modules')
}
Copy the code

2. IgnorePlugin (available in production)

Avoid introducing useless modules

import moment from 'moment'
Copy the code

All language JS code is introduced by default, which is too large

// Ignore the /locale directory under moment
new webpack.IgnorePlugin(/\.\/locale/./moment/)
Copy the code

Then manually import the required language packs

3. NoParse (available in production environment)

Avoid double packing

module: {
    // The entire 'react.min.js' file is not modularized
    // Ignore recursive parsing of 'react.min.js' files
    noParse: [/react\.min\.js$/],}Copy the code
IgnorePlugin is not introduced directly, noParse is not introduced in the code, but is not packagedCopy the code

4. HappyPack Multi-process packaging (available for production)

JS single thread, enable multi-process packaging

Improved build speed (especially on multi-core cpus)

rules: {
    test: /\.js$/.// pass processing of.js files to the HappyPack instance with id Babel
    use: ['happypack/loader? id=babel'].
    exclude: /node_modules/
}
plugins: {
    // Enable multi-process packaging
    new HappyPack({
        // Use a unique identifier id to indicate that the current HappyPack is used to process a specific class of files
        id: 'babel'.// How to handle.js files, which are used in the same way as in Loader configuration
        loaders: ['babel-loader? cacheDirectory']})}Copy the code

The ParallelUglifyPlugin can be used in production environments.

Webpack has built-in UglifyJS tool compression

UglifyJS compression is still used, but it helps to start multiple processes

For production use, the development environment does not need to be compressed

About starting multiple processes

For large projects with slow packaging, enabling multiple processes can increase speed. For small projects with fast packaging, enabling multiple processes can reduce speed (process overhead) and be used on demandCopy the code

6. Automatic refresh (not available in production environment)

The whole page is refreshed, the speed is slow, the status will be lost

module.export = {
    watch: true.watchOptions: {
        ignored: /node_modules/,
        aggregateTimeout: 300.poll: 1000}}Copy the code

7, hot update (not for production environment)

The new code takes effect, the page does not refresh, the state does not lose

DllPlugin plugin for dynamic link library (not available in production environment)

Front-end frameworks, such as Vue React, are large in size, slow in construction and stable, and can be built once for the same version rather than rebuilt every timeCopy the code

Webpack has built-in DllPlugin support

DllPlugin - Package out DLL files and generate manifest.json DllReferencePlugin - Use DLL filesCopy the code
Copy the code

Optimize output code (product performance)

Smaller volume reasonable subcontracting, no repeated loading faster, less memory useCopy the code

Small picture base64 encoding

ConentHash generates a hash value based on the contents of the file

Lazy loading

Extract common code

IngorePlugin

Use CDN acceleration

1. Set publicPath to the CDN address

2. Upload the packaged file to the CDN

Using the mode: production

1. Automatically enable code compression

Vue React delete debug code (such as warning in development environment)

3, automatically start tree-shaking (unused, unreferenced code is not packaged, the size of the packaged code is smaller)

Note: ES6 Module lets tree-shaking work, not commonJs

ES6 Module is different from Commonjs
1ES6 Module is statically introduced at compile time2, Commonjs dynamic import, import at execution3Only ES6 Modules can be statically analyzed, realizing tree-shakingCopy the code

Scope collieries (merge function)

Code size is smaller, create functions with less scope and code readability is betterCopy the code
module.exports = {
    // For third party modules in Npm, the ES6 modular syntax of JsNext: Main is preferred
    resolve: {
        mainFields: ['jsnext:main'.'browser'.'main']},plugins: {
        // Start the Scope collieries
        new ModuleConcatenationPlugin(),
    }
}
Copy the code

babel

1. Basic configuration

. Babelrc configuration

Presets and plugins

{
    // The Babel plugin collection
    "presets": [["@babel/preset-env"]],"plugins": []}Copy the code

2, Babel – polyfill

A collection of core-js and Regenerator

Deprecated babel-Polyfill after Babel7.4

import '@babel/polyfill'
const sum = (a, b) = > a + b
/ / the new API
Promise.resolve(100).then(data= > data)
/ / the new API
[10.20.30].includes(20)

// ES5 syntax
// Do not handle modularity (webpack)
Copy the code

The babel-Polyfill file is large and the configuration is brought in on demand

{
    // The Babel plugin collection
    "presets": [["@babel/preset-env",
            {
                "useBuiltIns": "usage"."corejs": 3}]],"plugins": []}Copy the code

3, Babel – the runtime

Babel – polyfill

1, will pollute the global environment2If you do an independent Web system, barrier-free3Doing a third party library can be problematicCopy the code

Solve global environmental pollution problems with Babel-Runtime

{
    // The Babel plugin collection
    "presets": [["@babel/preset-env",
            {
                "useBuiltIns": "usage"."corejs": 3}]],"plugins": [
        "@babel/plugin-transform-runtime",
        {
            "absoluteRuntime": false."corejs": 3."helpers": true."regenerator": true."useESModules": false}}]Copy the code