See the notes for details

Why use Webpack?

Look at the official explanation and go back in history, how have projects been developed before

The first stage

(1) A large number of <script> tags are referenced in every HTML file

This approach creates network bottlenecks and loads a lot of useless code

(2) Only introduce one JS file, which contains all the code of the whole project, tens of thousands or even hundreds of thousands of lines of code. This leads to scopes that are indistinguishable and difficult to maintain

The second stage

IIFE immediately executes the function(function(){})() to resolve scope issues for large projects. Grunt and Gulp use this pattern. Of course, there are some problems with this, such as changing a file and having to rebuild the entire project. When introducing a third party library, even if only a small amount of code is needed, the whole third party library code must be introduced, and code segmentation cannot be achieved.

The third stage

Use Webpack (essentially, Webpack is just a static module packaging tool)

Of course, Webpack is based on the following basic conditions or inspirations (1) the creation of Node.js to run in calculators and services outside the browser (2) common.js introduced the require mechanism, Allows other modules to be loaded in the current file (browsers do not support common.js’ module mechanism, so packaging tools like Browserify, RequireJS and SystemJS allow us to write common.js modules that run in the browser)

2. Basic use of Webpack

View Official Documentation

(1) Install Webpack and Webpack-CLI

npm install webpack webpack-cli --save-dev

(2) Create the configuration file

Create three files in the root directory

  • webpack.common.js
  • webpack.dev.js
  • webpack.prod.js

Then modify package.json

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "webpack --watch",
    "start": "webpack serve --open --config webpack.dev.js",
    "build": "webpack --config webpack.prod.js"
  },

This way, you can use different configurations for NPM run start and NPM run build

webpack.common.js Specific code

const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const { resolve } = require("path"); / * usually module. Exports = {... */ module.exports=(env)=>{} when you type webpack --env envName on the command line, exports=(env)=> ({entry: () => new Promise((resolve) => { setTimeout(() => { resolve({ index: { import: "./src/index.js" }, print: { import: "./src/print.js" }, }); }, 50); }), output: { filename: "js/[name].[contenthash].js", path: path.resolve(__dirname, "dist"), clean: true, pathinfo: False, // package the project as a library (add module: SRC /index.js to package.json to allow the library to be referenced using import) // Library: {// Name: "libraryName", // type: Js (const library=require("library")), ADM([require("library"),function(library){}]), script tag reference //},}, Module: {rules: [{test: /\.css$/ I, // include: path.resolve(__dirname, "SRC "), // contain directory use: [ // path.resolve(__dirname, "webpackLoaders/aLoader/a-load.js"), "style-loader", "css-loader", ], }, { test: / \. (PNG | SVG | JPG jpeg | | GIF) $/ I type: "asset/resource / / webpack5 x built-in, used for handling static resources}, {test: / \. (woff | woff2 | eot | the vera.ttf | otf) $/ I type: "asset/resource / / webpack5 x built-in, used for handling static resources},],}, optimization: {// When a new file is introduced, it does not change the original chunk module.id. The previous chunk hash is worth preserving. "Deterministic ", /* runtimeChunk:single means that C. Js (export default {count:0}) will only be instantiated once if A. Js and B. Js are both instantiated together. If the HTML loads both a and b JS, then count++ is executed twice. If runtimeChunk is not set, C.js instantiates it twice, A, b two js execution count++ each other runtimeChunk: single purpose is to save the data reference documentation: https://bundlers.tooling.report/code-splitting/multi-entry/ * / RuntimeChunk: "single", // SplitchPunks: {chunks: "all", cacheGroups: {vendor: { test: /[\\/]node_modules[\\/]/, name: "vendorName", chunks: "All ",},},},},},}, // externals: // externals: {// lodash: {// commonjs: "lodash", // commonjs2: "lodash", // amd: "lodash", // root: "_", // }, // }, plugins: [ new HtmlWebpackPlugin({ title: "development", }), ], });

webpack.dev.js Specific code

const path = require("path"); const { merge } = require("webpack-merge"); const common = require("./webpack.common.js")(); const HandleConsole = require("./webpackPlugins/handleConsole.js"); const config = merge(common, { mode: "development", devtool: "inline-source-map", devServer: { contentBase: "./dist", hot: true, }, module: { rules: [ { test: /\.text$/i, loader: path.resolve(__dirname, "webpackLoaders/aLoader/a-load.js"), }, ], }, // plugins: [new HandleConsole({ test: 123})]}); module.exports = config;

webpack.prod.js The relevant code

const { merge } = require("webpack-merge");
const common = require("./webpack.common.js")();

module.exports = merge(common, {
  mode: "product",
  // devtool: "inline-source-map",
});

3. Webpack packaging library

The general operation is the same as above, only need to configure the Library in Output

output: { library: { name: "libraryName", type: "Umd ",// compatible with common.js(const library=require("library")), ADM([require("library"),function(library){}]), script tag reference},}

If you want to refer to the library as an import, add “module”: “SRC /index.js” to package.json

4. Develop Webpack-loader

5. Develop webpack-plugin