Definition 1.

Webpack is a static JS module bundler.

Starting from the entry module, recursively look for the dependencies of all files and package the entry and all dependencies into one file. It is the embodiment of the idea of engineering automation.

2. Install

Local install (recommended, does not conflict with global)

NPM install --save-dev webpack -- cli --save-dev webpack -- cli4.X Stable version NPM i-d webpack@<version> NPM i-d webpack@4.44. 0 


// Recommend the relevant version of 4
//[email protected], [email protected], webpack-dev-server:@3.11.0

Copy the code

Global installation

When installing Webpack V4+, Install webpack-cli NPM install webpack webpack-cli -g # Check the version webpack -v # Uninstall NPM uninstall webpack webpack-cli -gCopy the code

3. Support

  • Webpack supports JS and JSON modules by default
  • Supports module types such as CommonJS Es Moudule AMD
  • Webpack4 supports the use of zero configuration, but it is weak, and slightly more complex scenarios require additional extensions and are recommended to be rewritten

Example:

//index.js
const json = require("./index.json");//commonJS
import { add } from "./other.js";//es module
console.log(json, add(2.3));
//index.json
{
    "name": "JOSN"
}
// other.js
export function add(n1, n2) {
    return n1 + n2;
}

// The default configuration information is automatically generated webpack.config.js
const path = require("path");
module.exports = {
    // Mandatory webPack execution build entry
    entry: "./src/index.js".output: {
        // Merge all dependent modules into main.js
        filename: "main.js".// The path where the output file is stored must be an absolute path
        path: path.resolve(__dirname, "./dist")}};Copy the code

4. Start

Start in NPX mode

The idea is to create a soft link in the node_modules/.bin directory using a shell script.

npx webpack 
Copy the code

NPM script to start

npm run test
Copy the code

5. Configuration description

module.exports = {
    entry: "./src/index.js".// Package the entry file
    output: "./dist".// Output structure
    mode: "production".// Package the environment
    module: {
        rules: [
            // Loader module processing
            {
                test: /\.css$/,
                use: "style-loader"}},plugins: [new HtmlWebpackPlugin()] // Plug-in configuration
}; 

Copy the code

entry

// Single-entry SPA, which is essentially a string
entry: {
    main: './src/index.js'
}
/ / equivalent to the
entry: "./src/index.js"

// The array is also a single page and eventually only one bunlde
entry: ["./src/index.js"."./src/login.js"] 


// Entry is the output of the object under [name] directly output here named index and login
entry: {
    index: "./src/index.js".login: "./src/login.js"
}
Copy the code

output

/ / a single entrance
output: {
    filename: "bundle.js".// Name of the output file
    path: path.resolve(__dirname, "dist")// Output file to the disk directory, must be an absolute path
},
[name] = entry {index: and login:}
output: {
    filename: "[name][chunkhash:8].js".// Use placeholders and do not duplicate file names
    path: path.resolve(__dirname, "dist")// Output file to the disk directory, must be an absolute path
},

Copy the code

mode

The Mode command specifies the current build environment

  • production
  • development
  • none

use

//1. The configuration definition is recommended
module.exports = {
  mode: 'production'
}; 
//2. Parameter startup. If the parameter startup is modified later, it will still be overwritten here, which is easy to confuse
webpack --mode=production
Copy the code

The effect after setting

mode: 'develop' 
/ / equivalent to the
module.exports = {
     mode: 'development'.plugins: [
     new webpack.NamedModulesPlugin(),
    new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("development")})]}// 'development' sets the value of 'process.env.node_env' in 'DefinePlugin' to 'development'.
// Enable 'NamedChunksPlugin' and 'NamedModulesPlugin'

mode: 'production' 
/ / equivalent to the
module.exports = {
    mode: 'production'.plugins: [
        new UglifyJsPlugin(/ *... * /),
        new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("production")}),new webpack.optimize.ModuleConcatenationPlugin(),
        new webpack.NoEmitOnErrorsPlugin()
    ]
}
    
/ / production | will ` process. The env. NODE_ENV ` value set to ` production `.
/ / enabled ` FlagDependencyUsagePlugin `, ` FlagIncludedChunksPlugin `, ` ModuleConcatenationPlugin `,
// 'NoEmitOnErrorsPlugin', 'OccurrenceOrderPlugin', 'SideEffectsFlagPlugin' and 'UglifyJsPlugin'.
Copy the code

loader

Webpack only knows how to handle JS and JSON modules by default, so other formats of module processing, and processing methods need loader

  • The following csS-Loader code generates a style tag and inserts it into the page
  • Css-loader // just lets WebPack support CSS parsing
  • less-loader
  • sass-loader
  • Ts-loader // Converts TS to JS
  • Babel-loader // converts ES6, 7 and other JS new feature syntax
  • File-loader // Processes picture subgraphs
  • eslint-loader

moudle

Everything in Webpack is a module, and a module corresponds to a file. Webpack will recursively find all dependent modules from the configured Entry.

When webPack processes an unknown module, you need to configure the Module in WebPack, and when the module format is detected, which loader is used to process the module.

module: {
    rules: [{test: /\.xxx$/.// Specify a matching rule
            use: {
                loader: 'xxx-load'// Specify the loader to use}}}]// Style module transform example
// css-Loader analyzes the relationships between CSS modules and synthesizes a CSS
// The style-loader will mount the content generated by the CSS-Loader to the heade section of the page in Style
// Note that the execution sequence is from right to left
//npm install style-loader css-loader -D
{
    test: /\.css$/,
    use: ["style-loader"."css-loader"]}//npm install vue-loader -D
/ /. Example vue
{
    test: /\.vue$/,
    use: ["vue-loader"."css-loader"]}Copy the code

Plugins extend

The WebPack packaging process has hooks (lifecycle concepts)

Plugins can help you do something when WebPack is running at a certain stage. Similar to the concept of lifecycle extensions, plugins inject extension logic at specific points in the WebPack build process to change the build result or do what you want. Applies to the entire build process

Example:

const path = require("path");
const htmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
    ...
    plugins: [
        new htmlWebpackPlugin({
            title: "My App".filename: "app.html".template: "./src/index.html"}})];/ / index. The HTML below by % > < % = htmlWebpackPlugin. The options. The title can take to htmlWebpackPlugin set of information
< !DOCTYPE html >
    <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
            <meta http-equiv="X-UA-Compatible" content="ie=edge" />
            <title><%= htmlWebpackPlugin.options.title %></title>
        </head>
        <body>
            <div id="root"></div>
        </body>
    </html>
Copy the code

bundle

The final output file after the resource is parsed and compiled by the Webpack process. For the main commonly. Js

chunk

A chunk of code. A chunk may consist of several modules. It is also used for code merging or splitting.

When a page has multiple js references, multiple modules are assigned to chunks within a bundle

6. Module,chunk, and bundle

Js, utils.js, common.js, and index.css are introduced into the SRC directory. The directory structure is as follows:

SRC / ├── index.css ├─ index.html ├─ index.js ├─ common.js ├─ utils.jsCopy the code

Index. CSS write a simple style:

body {
    background-color: red;
}
Copy the code

Write a utility function to square the utils.js file:

export function square(x) {
    return x * x;
}
Copy the code

Write a log function to the common.js file:

module.exports = {
  log: (msg) => {
    console.log('hello ', msg)
  }
}
Copy the code

Make some simple changes to the index.js file and introduce the CSS file and common.js:

import './index.css';
const { log } = require('./common');

log('webpack');
Copy the code

Webpack is configured as follows:

{ entry: { index: ".. /src/index.js", utils: '.. / SRC /utils.js',}, output: {filename: "[name].bundle.js", // Output: {filename: "[name].bundle.js", // Module: {rules: [{test: /.css$/, use: [MiniCssExtractPlugin. Loader, / / to create a link tags' CSS - loader, / / CSS - loader is responsible for parsing the CSS code, processing of the dependence of CSS],},]} plugins: New MiniCssExtractPlugin({filename: 'index.bundle.css' // Output CSS file named index.css}),]}Copy the code

Let’s run WebPack and see the result:

As we can see, index.css and common.js are introduced in index.js, and the generated index.bundle. CSS and index.bundle.js are both in chunk 0, utils.js because they are packaged separately. It generates utils.bundle.js, which belongs to Chunk 1.

conclusion

Module, chunk, and bundle are the same piece of logical code with three different names in different conversion scenarios:

  • What we write directly is a module, our own code, a single file
  • The webpack process is chunk, and chunk combines all related referenced files into one chunk
  • Finally, the bundle is generated that the browser can run directly. A bundle is a chunk, but you can use plugins to separate multiple bundles from a chunk