About webpack

Time:2021-7-27

brief introduction

In essence, webpack is a static module packaging tool for modern JavaScript applications. When each application relies on one or more of the required webp bundles, it generates one or more of them internally

Official website: https://webpack.docschina.org/

New features of webpack 4

1. Mode attribute: development or production (if mode is not set, it is production by default)
   For example: webpack -- mode development / production
   
   Features for development mode:
   Browser debugging tool
   Comments, detailed error logs and tips for the development phase
   Fast and optimized incremental construction mechanism
   
   Features available for production mode:
   Open all optimization codes
   Smaller bundle size
   Remove code that only runs during the development phase
   Scope hoisting (put multiple bundles into a large closure to speed up the running speed of the whole code) and tree shaking (remove unused modules)
   
2. Plug in and optimization
   The Commons chunkplugin plug-in was removed
   It uses the built-in APIs optimization.splitchunks and optimization.runtimechunk, which means that webpack will generate shared code blocks for you by default
   Changes in other plug-ins:

About webpack

3. Webassembly out of the box
   This results in a significant increase in runtime performance
   You can directly import or export the local wasm module, or directly import C + +, C or rust by writing loaders
   
4. Support multiple module types (5 types)

About webpack

5. 0CJS
  It means 0 configuration. Webpack.config.js is no longer forced to be used as the packaged entry configuration file
  Its default entry is'. / SRC / 'and default exit is'. / dist', which is good news for small projects
  But it is still highly configurable and can meet your needs
  
6. New plug-in system
   New APIs for plug-ins and hooks are provided
   The changes are as follows:

About webpack

Note: when using webpack4, make sure that the version of node.js used is above 8.9.4

Install webpack

Enter the command in CMD: NPM install webpack cli - G (Global installation is not recommended)

If you want to use the webpack 4 + version, you also need to install webpack cli: NPM install -- save dev webpack cli

Basic use of webpack

Packaging command: webpack -- mode development / production input file.js - O output file.js

Webpack — entry exit configuration file

Configuration file webpack.config.js:
const path=require('path');
//Configuration when a file is packaged
module.exports={    
    Entry: 'input file name',  
    output:{
        path:path.resolve(__ Dirname, 'dist'), // directory path of output file
        Filename: 'output file name'
    },
    mode:'production/development'
}

//Configuration when multiple files are packaged 
module.exports={    
    Entry: {// when multiple files
        XXX: 'input file 1',
        XXXX: 'input file 2',
        ...
    },
    output:{
        path:path.resolve(__ Dirname, 'dist'), // directory path of output file
        Filename: '[name]. XXX. JS' // dynamic output file name
    },
    Mode: 'production / development', // mode
    Module: {}, // module: such as parsing CSS, how to convert and compress images
    Plugins: [], // plugins: used for production modules and various functions
}

Open CMD, enter the directory where webpack.config.js is stored, and enter the command webpack to package

Webpack — loader URL loader

Function: when a file size is smaller than a specified size, it will be automatically converted to the form of dataurl (Base64 by default)

Installation: NPM install URL loader -- save dev

Webpack.config.js file configuration:
module.exports = {
    module: {
        rules: [
        {
            Test: / (png|jpg|gif) $/ I, // matched picture form
            use: [
            {
                loader: 'url-loader',
                options: {
                    // if the URL size is less than 8192, it will be automatically converted to the format of datasize (if the value is less than 8192, it can be automatically converted)
                    Encoding: Specifies the encoding form
                },
            },
            ],
        },
        ],
    },
};

Webpack — loader Babel loader

Function: convert ES6, ES7... Code into Es5 code that can run in the browser

Installation: NPM install - D Babel loader @ Babel / core @ Babel / preset env webpack

Webpack.config.js file configuration:
module.exports = {
    module: {
        rules: [
        {
            Test: /. M? JS $/, // matching file extension
            exclude: /(node_ modules|bower_ Components) /, // excluded folders
            use: {
                loader: 'babel-loader',
                options: {
                    Presets: ['@ Babel / preset env'], // conversion rules
                    Plugin: [] // configure related plug-ins
                }
            }
        }
        ]
    }
}

Webpack — loader sass loader

Function: load sass / SCSS files and compile them into CSS

Installation: NPM install sass loader sass webpack -- save dev
(DART sass or node sass needs to be installed in advance for sass loader. This can control all dependent versions and freely choose the sass implementation to use.)

Webpack.config.js file configuration:
module.exports = {
    module: {
        rules: [
        {
            Test: /. S [AC] SS $/ I, // matching sass / SCSS files
            Use: [// install the following modules
                "Style loader", // generate the JS string into a style node (used to handle the URL () in the CSS file and mount the URL into JS)
                "CSS loader", // convert CSS into commonjs module (insert CSS into the style tag of the page)
                "Sass loader", // compile sass into CSS
            ],
        },
        ],
    },
};

Webpack — about the plug-in minicssextractplugin

Function: extract CSS into a separate file, create a CSS file for each JS file containing CSS, and support the on-demand loading of CSS and sourcemaps

Installation: NPM install -- save dev Mini CSS extract plugin

Webpack.config.js file configuration:
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
    Plugins: [new minicssextractplugin ({filename: XXX (determines the name of each CSS file output), chunkfilename: XXX (determines the name of a chunk file that is not an entry),...})],
    module: {
        rules: [
        {
            test: /.css$/i,
            use: [MiniCssExtractPlugin.loader, 'css-loader'],
        },
        ],
    },
};

When this plug-in is used with sass loader, the configuration of the webpack.config.js file:
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
    module: {
        rules: [
        {
            test: /.s[ac]ss$/i,
            use: [
                process.env.NODE_ENV !== "production" ? "style-loader": MiniCssExtractPlugin.loader,
                "css-loader",
                "sass-loader",
            ],
        },
        ],
    },
    plugins: [new MiniCssExtractPlugin({filename: "[name].css", chunkFilename: "[id].css",...})],
};

Webpack — about the plug-in defineplugin

Function: allows the creation of configured global constants during compilation, avoiding code redundancy and increasing flexibility
      This is very useful when you need to distinguish between development mode and production mode for different operations

use:
var webpack=require('webpack');
New webpack. Defineplugin ({corresponding constant: corresponding value});

About webpack

Webpack — about the plug-in htmlwebpackplugin

Function: it simplifies the creation of HTML files to provide services for your webpack package (HTML file packaging)
      This is particularly useful for webpack packages where the file name contains a hash value that changes with each compilation
      You can let the plug-in generate an HTML file for you, use the lodash template to provide the template, or use your own loader
      
Installation: NPM install -- save dev HTML webpack plugin

Webpack.config.js file configuration:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
    Entry: 'entry file name',
    output: {
        path: path.resolve(__dirname, './dist'),
        Filename: 'export file name',
    },
    plugins: [new HtmlWebpackPlugin({
                title:'xxxx',  //
                Filename: 'xxx. HTML', // generated (output) HTML file name
                Template: 'XX. HTML' // the input HTML file (you can directly write <% htmlwebpackplugin. Options. Title% > under the file to reference the title)
    })],
};
This dist.html file will contain the following contents:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>xxxx</title>
    </head>
    <body>
        <script></script>
    </body>
</html>

About webpack

When multiple HTML pages are packaged:

About webpack

Webpack — hot replacement

You need a plug-in: webpack dev server
Function: the content displayed by the server will be updated in real time

Installation: NPM install webpack dev server - D

Webpack.config.js file configuration:
module.exports = {
    //...
    devServer: {
        contentBase: path.join(__ Dirname, 'dist'), // directory of the target file
        Compress: true, // whether to enable gzip compression
        Port: 9000, // target port
        Hot: true // whether to hot replace (real-time update) (webpack4 does not need to describe the configuration of this attribute)
    },
};

In the package.json configuration file:
"scripts":{"start":"webpack-dev-server"}

Webpack — CSS3 prefix
About webpack

Webpack —- packaging of pictures in HTML and CSS

Picture packaging in CSS:

About webpack

Picture packaging in HTML:

About webpack

Webpack —- clear unused CSS
About webpack

Webpack — package comments

New webpack. Bannerplugin ('xxxx (comment))

Webpack —- modular configuration of portal file
About webpack

Webpack — development environment and production environment

Devdependencies (development environment) stores the package on which the test code depends or the package of the build tool
The dependencies (production environment) stores the packages that the project or component code depends on

Install all project dependent packages: NPM install
Install the production environment dependency package: NPM install -- production

Webpack —- resource copy

Some development technical documents can be copied directly

About webpack