[TOC]

modular

Modularity is just thought

Unmodular issues:

  • Contamination global scope
  • Naming conflicts
  • Unable to manage documents scientifically

Solution: Modular specification + module loader

The module specification

CommonJS

  • A file is a module
  • Each module has a separate scope
  • Exports members through module.exports
  • Load the module via the require function

ES Modules

Using the environment

CommonJS used NodeJS

ES Modules are used for Browers

ES Module(ESM)

features

  • Automatically adopt strict mode, ignoring ‘use strict’
  • Each module has a private scope that cannot be accessed by outsiders
  • The ESM can only request external JS modules through CORS
  • ESM delays script tags from running script code

Import and export

Simple export

var name = "module_A";
function f() {
    alert("function f()");
}

/ / export
export {name,f};

// You can also rename the exported section for ease of use
export {f as fun};
Copy the code

Simple import

/ / import
import {name,f} from "./module_A.js"
f();
console.log(name);

// You can also rename it for your own use
import {name as aaa} from "./module_A.js"
Copy the code

Import Precautions

  1. Imported curly braces are not shorthand for object literals, but fixed syntax
import {} from ""
Copy the code
  1. When you import data, instead of copying the module data, you import the module data in

  2. The data type of the obtained module data is const

  3. When importing modules, write the full name of the module path, including the prefix./ or.. / and the suffix.js

  4. The path import can only be “./**/*.js”, and the arguments cannot be identified

  5. Statements such as if cannot determine whether to import a module. The dynamic loading method is as follows

var module_A;

import("./**/module_A.js").then((module) = >{
    if(/* Determine the condition */)
       module_A = module;
})
Copy the code
  1. Import the defaultexport defaultway
import abc form "./**/*.js"
// ABC is the value exported by export default
Copy the code

Export Precautions

  1. The exported curly braces are not shorthand for object literals, but fixed syntax
export {}
Copy the code
export default {}
Copy the code

Export default can be followed by a variable, including an object literal

  1. If there are multiple components or modules in the same directory, you are advised to create an index file and export all the files in the same directory so that developers can operate files in the same directory
export {Module_A} from "./Module_A.js"
export {Module_B} from "./Module_B.js"
export {Module_C} from "./Module_C.js"
Copy the code

Combination of sexual

The browser-es-module-loader plug-in is used to get older browsers to work

Plug-in: github.com/ModuleLoade…

Quick use:

  1. Find the first two sections of the core

<script src="dist/babel-browser-build.js"></script>
<script src="dist/browser-es-module-loader.js"></script>
Copy the code
  1. Enter the plug-in name browser-es-module-loader after unpkg.com/

Wait a moment, you will enter the latest version of the plug-in address, such as: unpkg.com/browse/brow…

  1. Find the corresponding file of the core code and import it into an HTML file
 <script nomodule src="https://unpkg.com/[email protected]/dist/babel-browser-build.js"></script>
  <script nomodule src="https://unpkg.com/[email protected]/dist/browser-es-module-loader.js"></script>
Copy the code

Note: If the browser does not support polyfill, use the promise-Polyfill plug-in

Find and use browser-es-module-loader

  <script nomodule src="https://unpkg.com/[email protected]/dist/polyfill.min.js"></script>
Copy the code

NodeJS is used in ESM

The MJS final syllable

To run ESM js normally, change the suffix. Js to. MJS for easy node identification

Terminal command line

node *.mjs --experimental-modules
Copy the code

If the nodeJS version is higher, you can omit –experimental-modules

You can use the Node built-in module directly from within the MJS file

// Node built-in modules can be exported completely or destructively

/ / all
import fs from 'fs'
fs.writeFileSync('./foo.txt'.'es module working')

/ / deconstruction
import { writeFileSync } from 'fs'
writeFileSync('./bar.txt'.'es module working')
Copy the code

You can use node third-party modules

// Note: third-party modules can only be exported completely, not deconstructed
// The reason for this failure is that third-party modules do not specifically export individual module members
import _ from 'lodash'
_.camelCase('ES Module')

// The following is the wrong example
/* import { camelCase } from 'lodash' console.log(camelCase('ES Module')) */
Copy the code

Import/export relationship between CommonJS and ESM

  • CommonJS modules can be imported into ES Module
  • You cannot import ES Module modules in CommonJS
  • CommonJS always exports only one default member
  • Note that import does not deconstruct the exported object

Modify the default JS running rules

In the default package.json file, there is a property called “type” that determines the mode in which the default JS file will run

Attribute values instructions Another rule
CommonJS or not fill By default, commonJS rules run ESM .mjs
module By default, it runs according to ESM rules CommondJS .cjs

Babel is compatible with ESM methods

As before, install the configuration environment

# preset is not @babel/preset-env, Instead, @babel/plugin-transform-modules-commonjs NPM I -d @babel/core @babel/node @babel/plugin-transform-modules-commonjsCopy the code

Then configure the syntax rule. Babelrc file

{
  "plugins": [
    "@babel/plugin-transform-modules-commonjs"]}Copy the code

webpack

Why module packaging tools

If this is the case, each request will access a module once, which will increase the server load and affect network speed. Therefore, a toolkit is needed to package all modules in the development phase and change the access module to internal access

General process of packaging:

ES6 => ES5 => Same file

function

Module compatibility => Module Loader

Multi-module packaging => Module bundle

File Splitting => Code Splitting

Other non-JS files => Asset Module

Based on using

Simple introduction

  • Initialize the project in a directory
npm init --yes
Copy the code
  • Install ** Webpack ** and its scaffolding
# NPM NPM I -d webpack webpack-cli # yarn add --dev webpack webpack-cliCopy the code
  • Create a new SRC directory in your project and write several js files to export and import in index.js

  • Finally use Webpack packaging

# yarn method yarn webpackCopy the code
  • Once the package is complete, there will be a dist directory, which is the packed JS file

The configuration file

It is a simple start, but many details are not perfect, such as only reading./src.index.js files, can not package other resource files (such as CSS, HTML, images, etc.)

So you use configuration files, and you pack everything in your project

  1. Create a new webpack.config.js file (within the project)

  2. The configuration file

const path = requir("path")
// Configure specifications:
module.export = {
    entry: "./src/main.js".// Set the package entry (run entry), if relative path './' cannot be omitted
    output: {  // Output configuration, note: this can only be an object, not another data type
        filename:"bundle.js".// Output the file name
        // The output path must be an absolute path
        path:path.join(__dirname,"output")}}Copy the code

Summary of input and output:

The property name instructions example
entry This is the packing entrance

Note: the ‘./’ of absolute paths cannot be omitted
entry: “./src/main.js”
output Output configuration

Note: This can only be an object, not another data type
-filename An attribute in the output object

Output file name
filename:”bundle.js”
-path An attribute in the output object

The output path must be an absolute path
path:path.join(__dirname,”output”)

Working mode

Webpack packaging comes in several forms

  • Development mode

yarn webpack –mode development

Packaged js file ▼

  • Product Model (online model)

yarn webpack –mode production

Packaged js file ▼

  • Packing without any processing

yarn webpack –mode none

Packaged js file ▼

For ease of use, this property can be written in a configuration file (webpack.config.js)

const path = require('path')

module.exports = {
  // The configuration is here
  mode: 'development'.// The configuration is here
  entry: './src/main.js'.output: {
    filename: 'bundle.js'.path: path.join(__dirname, 'dist')}}Copy the code
The mode attribute value instructions The effect
development Development mode Optimize packing speed

Add some debugging AIDS
production Production mode Optimized packaging results
none None mode Original packaging, no processing

Packing CSS files

The original Webpack can only package JS files. If you want to package CSS files, you need another module loader.

To package CSS files, you need csS-loader and style-loader to package CSS files into JS files.

If an HTML file is used, import it using the script tag

Configuration file (webpack.config.js)

const path = require("path")
module.exports = {
    mode:"none".// Change the package entry to the CSS file directory
    entry: "./css/index.css".output: {
// It is a js file, not a CSS file
        filename: "index.js".path: path.join(__dirname,"dist/css")},// Configure the packaging properties
    module: {rules:[
            {
           	// Identify the file format
                test:/.css$/ ,
            // Specify the packaged module loader
            // Note that the running order is from back to front, not front to back!!
                use:[
                    "style-loader"."css-loader"}]}}Copy the code

According to the configuration file above, the packing location is./dist/ CSS /index.js, and the HTML file is imported

  <script src="./dist/css/index.js"></script>
Copy the code

Import resource files through JS and package them

You can import CSS files from JS files and package them together

import './main.css'

module.export = {
    ......
}
Copy the code

The configuration file

const path = require("path")
module.exports = {
    mode:"none".// The file entry is still a JS file, but the CSS file is packaged as well
    entry: "./src/index.js".output: {
        filename: "index.js".path: path.join(__dirname,"dist")},module: {rules:[
            {
                test:/.css$/ ,
                use:[
                    "style-loader"."css-loader"}]}}Copy the code

Pack other files

As with CSS files, you need a special module loader to package other files:

Module loader needed to package files: file-loader

# yarn
yarn add --dev file-loader

# npm 
npm i -D file-loader
Copy the code

As above, import through js file

The following is an example of importing a picture

import icon from ".. /images/icon.png"

export default() = > {const img = document.createElement("img");
    img.src = icon;
    return img;
}
Copy the code

The configuration file

module.exports = { ... .module: {rules:[
            {
              test:/.png$/ ,
              use:[
                  "file-loader"] {},// Other rules}}}]Copy the code

The final packaging

yarn webpack
Copy the code

Convert the file to a Base64 string through the URL loader

Browsers support Base64 conversion

So you can use Base64 to convert some files, such as small images, to (encrypted) strings

The browser decodes the file itself

Required module loader: url-loader

// Config file
module.exports = { ... . .module: {
    rules: [{......}, {test: /.png$/.// use can be expressed as an object
        use: {
          loader: 'url-loader'.options: {
            // Set the file valve to pack only files smaller than the valve
            limit: 10 * 1024 // 10 KB
            // Note: File-loader is required here
            // The purpose is to process files larger than the valve}}}]}}Copy the code

Specifications after packaging:

// The style of the packaged image can be displayed directly in the browser address bar
data:image/png; base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAAACXBIWXMAAAsSAAALEgHS3X78AAAgAElEQVR4nO3debwcVZn/8aeqbwIJRgISCEtEd tCg4MowCpFFMTjqoEjG+SlEDKjzExEGFVRCUHABUWFcABF0RicS3DGgLEJExI2ggOxbABGJIQgEktyumj9u973V1ae6T3VX1Tmnzuf9et1X7u3bXV3e0TlPn 3Oe8w3iOBYAAOCX0PQNAACA6lEAAADgIQoAAAA8RAEAAICHKAAAAPAQBQAAAB6iAAAAwEMUAAAAeIgCAAAAD1EAAADgIQoAAAA8RAEAAICHKAAAAPAQBQAAA B6iAAAAwEMUAAAAeIgCAAAAD1EAAADgIQoAAAA8RAEAAICHKAAAAPAQBQAAAB6iAAAAwEMUAAAAeIgCAAAAD1EAAADgIQoAAAA8RAEAAICHKAAAAPAQBQAAA B4aKfqC4WKZU/Q1AcBrzdFg4NdGo72vFTWD1vOCxHM6f9fxvGYg0ahI3P6+9XjcDCRqdj9XRCSKgo77iKNAms3u/0xx1P1YEMay0fRN5MmVl0enHfjXPv9pk UPhBYCI7Cgi55dwXQDwTxyLhA2dJ3a+pq0xqfVz67GwMfZz+zmN1jAQTx57ThyLjMQT38ep7+Mo9Vik/l0Udb9OJPFv4h4k7rznpI02Edl0a5F1zzwtIs/R+ ENAUxlLABeJyIMlXBcA/JI1KHY/ceL56dckB/+u57T+TQ/WycG9PZjHUWKwjyYeiyKRqDn2Fae/b/0ct35ujo491hydeDwanXhN+mv6zLHBX0Rk8pSNwrNuP 2qQPyPUCi8AonkyKiLvKvq6AOCVQQb/9OuTg3/cHshTn7qjSCSQid/FqX+TA32c+moP9FkDf3twbyZ/N9r5O9WXiMgWO4hM26zzP9MWO3wlOODoSfn/mFApa xPgtSJyfUnXBoD6Un2KVz9Reg7+489JX1MxvT8+A5AuAlKPdX3qTxcBqYE/OQPQa9BvJh6ftIHIljuJbKiY7W9M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ftcBP1nFQ7rQSOw3IMkPAGxRelsgBcCQojP+5Vb5x2O3a7/gb/eObfhrD/hZoT7KnfvJx1RT/oqjfZPr/VmDf7/1/vTgn8R6PwCUZVGZF6cAKEB87UV79X1S1BR56FbFen/qIJ9G+lCf5J6AjE1/mZ0AqiIgY7Mf6/0AYJtS2wLZA1CQ8Jz7vywzXvB+5S/XrRmL8F27ZuKxrGn1jgFasR+gPV3f8XtFD3/men9qs9/Q6/2J5/TD4A8AeZXWFsgMQEHiH336WGmu724LfPYpkUfuElm/NnuKvyvFL33C38jEz8lP/Om1f531fpL8AMAlpbUFMgNQoPCs24+SrXY9d/yBJ1eOneefFiQH1vb3iZ34qhkA1QE+WQf6JNfzOdwHAFz3oIhsH82T0SIvSgFQsPBbzzwlk6dsJKseFnn6cfWTOgb+xEAbpAbtrIFfuVygMeWvtd4vqeck7znxex0M/gBQlMLbAivPH669O67bUaZtdpA8vfpxiaPuETAIuyuuRiPueDwcEQlbP4eN9L8iQeKxsBFL0H5N6rnJ7xuJ/1OHI93PG3tO589h4jV5C8X0tQAAVmEGAAAAD7EJEAAAD1EAAADgIQoAAAA8RAEAAICHKAAAAPAQBQAAAB6iAAAAwEMUAAAAeIgCAAAAD1EAAADgIQoAAAA8RAEAAICHKAAAAPAQBQAAAB6iAAAAwEMUAAAAeIgCAAAAD1EAAADgIQoAAAA8RAEAAICHKAAAAPAQBQAAAB6iAAAAwEMUAAAAeIgCAAAAD1EAAADgIQoAAAA8RAEAAICHKAAAAPAQBQAAAB76P1qPPBje7iAbAAAAAElFTkSuQmCC
Copy the code

Common loader classification

Loaders fall into three categories:

  • Compiling conversion classes => Example: Convert a CSS file to a JS file
  • File operation => Example: Package an image file and change the path of the referenced image to the packaged path
  • Code checking classes => Example: eslint-loader checks JS code

Convert ES5

Webpack packaging does not convert ES6 + to ES5 the way Babel does

Therefore, it must be converted through the babel-loader module loader

# babel-loader @babel/core @babel/preset-env
yarn add babel-loader @babel/core @babel/preset-env --dev
# or
npm i -D babel-loader @babel/core @babel/preset-env
Copy the code

The configuration (webpack. Config. Js)

module.exports = { ... . .module: {rules:[{......}, {test: /.js$/ ,
                use: {
                // Select the loader
                	loader:"babel-loader".options: {// Set the Babel syntax conversion rule
                		presets: ["@babel/preset-env"}}}]}}Copy the code

Operating Principle (Operating principle)

Access the import file, import other files (modules) using import(ESM) or require(CommonJS) of the import file, and package them according to the different module loaders corresponding to the different files

Finally, the output is packaged to the dist directory (or other customized output path), and the package results are JS files and some large resource files

Example:

Entrance to the file


import './main.css'

import main from './main.html'

document.write(main)

Copy the code

The configuration file

const path = require('path')

module.exports = {
  mode: 'none'.entry: './src/main.js'.output: {
    filename: 'bundle.js'.path: path.join(__dirname, 'dist'),
    publicPath: 'dist/'
  },
  module: {
    rules: [{test: /.js$/,
        use: {
          loader: 'babel-loader'.options: {
            presets: ['@babel/preset-env'}}}, {test: /.css$/,
        use: [
          'style-loader'.'css-loader'] {},test: /.png$/,
        use: {
          loader: 'url-loader'.options: {
            limit: 10 * 1024 // 10 KB}}}, {test: /.html$/,
        use: {
          loader: 'html-loader'.options: {
            attrs: ['img:src'.'a:href'}}}]}}Copy the code

Create a new module loader

Create a JS file (preferably named xxx-loader.js) and follow these steps to build your own module loader

module.exports = source= > {
  / / content
    const content = ......
  return content
}
Copy the code

The configuration file

module.exports = { ... .module: {rules:[
            {
                // For example, identify TXT files
                test:/.txt/,
                use: ["./XXX-loader.js"]}, {... }}}]Copy the code

Example: Markdown file to HTML

const marked = require('marked')

module.exports = source= > {
  const html = marked(source)
  return html
}

Copy the code
const path = require('path')

module.exports = {
  mode: 'none'.entry: './src/main.js'.output: {
    filename: 'bundle.js'.path: path.join(__dirname, 'dist'),
    publicPath: 'dist/'
  },
  module: {
    rules: [{test: /.md$/,
        use: [
          'html-loader'.'./markdown-loader'}]}}Copy the code

Plugin

Responsible for solving other automation tools, such as: clean all files in target directory, copy static resources to target directory, compress output code, etc

Webpack + Plugin can accomplish most front-end engineering projects

Clear the contents of the directory before packing

If the package is in the same directory, if there are files in the previous directory, it is likely that the old file remains, affecting the packaging results (may be the size, or may pollute the previous files). In this case, we need a plug-in that can clean the directory files: clean-webpack-plugin

Usage: Add the plugins properties directly to the configuration file

const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

module.exports = {
  ......
  module: {
    rules: [...] },plugins: [
   // Create the required plug-ins
    new CleanWebpackPlugin()
  ]
}
Copy the code

Automatically generate HTML files

Previous packaging methods, methods are generated JS and other static resource modules, but do not support web page open (no HTML file) generation. In order for packaged projects to run properly in a browser, the html-webpack-plugin automatically generates HTML files

const path = require("path")
const {CleanWebpackPlugin} = require("clean-webpack-plugin")
const HtmlWebPackPlugin = require("html-webpack-plugin")

module.exports = {
    mode: "production".entry: "./src/main.js".output: {
        filename:"bundle.js".path:path.join(__dirname,"dist")},module: {
        rules:[
            {
                test:/.css$/,
                use:[
                    "style-loader"."css-loader"] {},test:/.png$|.jpg$/,
                use: [
                    {
                        loader:"url-loader".options: { 
                            // 10K
                            limit: 10*1024}}]}]},plugins: [new CleanWebpackPlugin(),
        new HtmlWebPackPlugin()
    ]
}
Copy the code

Where you can configure the internal attributes of the generated HTML file:

Such as:

const HtmlWebPackPlugin = require("html-webpack-plugin")

module.exports = {
    ......
    plugins: [new HtmlWebPackPlugin({
            // Set h1 header (subject)
            title: "test".// Set the meta attribute
            meta: {
                charset: "utf-8"
            },
            // Set the template HTML file location
            template:"./src/index.html".// Rename the file
            filename:"about.html"}})]Copy the code

Package static resource files

Plugin name: copy-webpack-plugin

const CopyWebpackPlugin = require('copy-webpack-plugin')

module.exports = {
    ......
    plugins: [new CopyWebpackPlugin([
          // Array indicates static file path
    	  // 'public/**' supports wildcards
      		'public'])]}Copy the code

Hook function

In the WebPack packaging process, there are many phases, and to make it easy for developers to add the required code at certain phases, WebPack expresses these phases as functions, where developers can add code to implement what they need

Partial hook functions:

entryOption

SyncBailHook
Copy the code

After the Entry configuration item is processed, execute the plug-in.

afterPlugins

SyncHook
Copy the code

After setting up the initial plug-in, execute the plug-in.

Parameters: the compiler

afterResolvers

SyncHook
Copy the code

After the resolver installation is complete, execute the plug-in.

Parameters: the compiler

environment

SyncHook
Copy the code

Once the environment is ready, execute the plug-in.

afterEnvironment

SyncHook
Copy the code

After the Environment installation is complete, execute the plug-in.

beforeRun

AsyncSeriesHook
Copy the code

Before compiler.run() is executed, add a hook.

Parameters: the compiler

run

AsyncSeriesHook
Copy the code

Hook into Compiler before starting to read records.

Parameters: the compiler

watchRun

AsyncSeriesHook
Copy the code

In listening mode, a plug-in is executed after a new compilation is triggered, but before the actual compilation begins.

Parameters: the compiler

normalModuleFactory

SyncHook
Copy the code

After NormalModuleFactory is created, execute the plug-in.

Parameters: normalModuleFactory

contextModuleFactory

After the ContextModuleFactory is created, the plug-in is executed.

Parameters: contextModuleFactory

beforeCompile

AsyncSeriesHook
Copy the code

After the compilation parameter is created, the plug-in is executed.

Parameters: compilationParams

compile

SyncHook
Copy the code

After a new compilation is created, the compiler is hooked into it.

Parameters: compilationParams

thisCompilation

SyncHook
Copy the code

Execute before triggering the compilation event (see the compilation below).

Parameters: the compilation

compilation

SyncHook
Copy the code

After creation, the plug-in is executed.

Parameters: the compilation

make

AsyncParallelHook
Copy the code

.

Parameters: the compilation

afterCompile

AsyncSeriesHook
Copy the code

.

Parameters: the compilation

shouldEmit

SyncBailHook
Copy the code

Return true/false.

Parameters: the compilation

needAdditionalPass

SyncBailHook
Copy the code

.

emit

AsyncSeriesHook
Copy the code

Before generating resources to the output directory.

Parameters: the compilation

afterEmit

AsyncSeriesHook
Copy the code

After generating the resource to the output directory.

Parameters: the compilation

done

SyncHook
Copy the code

The compilation is complete.

Parameters: the stats

failed

SyncHook
Copy the code

The compilation failed.

Parameters: the error

invalid

SyncHook
Copy the code

In listening mode, compilation is invalid.

Parameters: fileName, changeTime

watchClose

SyncHook
Copy the code

Listening mode stopped.

Development experience

— Watch automatic listening mode

This mode can be set only on the control terminal, for example, YARN webpack –watch

This allows you to monitor development files and automatically repackage them if they are modified

Automatic page refresh

Plugin name: webpack-dev-server

Effect: The modified file code can be refreshed automatically

Note: Webpack is not compatible with some webPack-CLI versions

Usage:

Yarn webpack serve # or write it in the scripts of package {......"start:dev":"webpack serve"
}
Copy the code

Static resource access

Two ways:

# This is recommended in the development phasemodule.exports->{ devServer }->{ contentBase:"Static file path"} # Not recommended during developmentconst CopyWebpackPlugin = require('copy-webpack-plugin')
module.exports->{ plugins }->[ new CopyWebpackPlugin(['Static file path'[)] # This will package the dist. Although webpack-dev-server can access the dist directly, repeated packaging will reduce development efficiencyCopy the code

Proxy services and support for cross-domain issues

# proxy methodmodule.export->{ devServer }
->{
    proxy: {
        "/api": {
             // http://localhost:8080/api/users -> https://api.github.com/api/users
             target: 'https://api.github.com'.// http://localhost:8080/api/users -> https://api.github.com/users
             pathRewrite: {
               '^/api': ' '
             },
             // Localhost :8080 cannot be used as the host name for requesting GitHub
             changeOrigin: true}}}Copy the code

Source Map

Function: record all functions and methods of packaging content when packaging, so as to facilitate the query of error parts after packaging

# Configure contentmodule.exports->{ devtool }->"source-map"
Copy the code

Effect:

When the browser console reports an error, you can directly locate the error location

Corresponding to find file, code line location

Of course, you can also use the debugger source to see what is wrong with the packaged JS file (not recommended).

Different packaging methods in Devtool mode

devtool

Attribute values
build

Build speed
rebuild

Build speed again
production

Whether the production environment is available
quality

Packaged type
(none) fastest fastest Y bundled code
eval fastest fastest N generated code
cheap-eval-source-map fast faster N transformed code(lines only)
cheap-module-eval-source-map slow faster N original source(lines only)
eval-source-map slowest fast N original source
cheap-source-map fast slow Y transformed code(lines only)
cheap-module-source-map slow slower Y original source(lines only)
inline-cheap-source-map fast slow N transformed code(lines only)
inline-cheap-module-source-map slow slower N original source(lines only)
source-map slowest slowest Y original source
inline-source-map slowest slowest N original source
hidden-source-map slowest slowest Y original source
nosources-source-map slowest slowest Y without source content

A simple understanding of the head:

Eval – Whether to use EVAL to execute module code

Cheap – Source map contains row and column information

Module – Whether to include source code before loader processing

It is recommended to use: cheap-module-eval-source-map when developing your environment

You are advised to use none in the production environment to prevent outsiders from stealing the fruits of their labor

Hot update HMR (HotModuleReplacement)

When the page changes, the previous input field, text input field will be automatically empty, if you want to see the input field, text input field CSS effect, you need to hot update to save previously written content

# # webpack configuration file with hot update, not only to configure the module properties, still need to import webpack HotModuleReplacementPlugin () objectmodule.exports->{ devServer }->{ hot:true} # import modeconst webpack = require("webpack");
module.exports->{ plugins }->[ new webpack.HotModuleReplacementPlugin() ]
Copy the code

But CSS can achieve hot update, the reason is that the packed CSS is rendered by the style tag, so it can be hot update (without refreshing the page), but JS files cannot be hot update, the reason is that JS files are irregular (in a framework, JS is divided by different files and modules, there are rules to follow).

Js module heat treatment

Module.hot.accept (” module relative position “, handle method)

Example #module.hot.accept("./editor", () = {console.log("Editor has been updated");
})
Copy the code

Of course, this method can achieve hot update, but can not retain the console information, especially error information, so the following can be written to ensure that the console information is retained, but there will be a little performance problem

if (module.hot) {
  let hotEditor = editor
  module.hot.accept('./editor.js'.() = > {
    // This function is automatically executed when editor.js is updated
    // Temporarily record the editor contents
    const value = hotEditor.innerHTML
    // Remove the element before the update
    document.body.removeChild(hotEditor)
    // Create a new editor
    // createEditor is now an updated function
    hotEditor = createEditor()
    // Restore editor content
    hotEditor.innerHTML = value
    // Append to the page
    document.body.appendChild(hotEditor)
  })

Copy the code

Image hot update

  module.hot.accept('./better.png'.() = > {
    // execute when better.png is updated
    // Overriding the SRC setting triggers a reload of the image element, thereby updating the image locally
    img.src = background
  })
Copy the code

Configuration files for different environments

Write different configuration files for different stages of development

Or package different solutions according to different needs

# webpack.common.js # public configuration # webpack.dev.js # webpack.production.js # other packaging schemesCopy the code

Other packaging solution templates:

const common = require('./webpack.common')

module.exports = Object.assign({},common,{
    // Overrides the previous same name attribute. })Copy the code

However, there is a problem with the plugins attribute. If you add a new attribute value to the original public attribute, you must write the plugins value again.

You are advised to use the Webpack-merge plug-in to avoid the above problems

const webpack = require('webpack')
const merge = require('webpack-merge')
const common = require('./webpack.common')

module.exports = merge(common, {
    // Overrides the previous same name attribute.// Add more attribute values
    plugins: [
        new. ] })Copy the code

Tree Shaking(Removing unreferenced code)

Tree Shaking is automatically used in production mode

Packaging in production mode automatically removes invalid codemodule.exports->{ mode:"production" }
Copy the code

Tree Shaking is generally not used in other packaging modes

Use the Tree Shaking method in other modesmodule.exports->{ optimization }->{ 
    // The module exports only used members
    usedExports: true ,
    // merge each module into the same function
    concatenateModules: true.// Compress the output
    // minimize: true
}
Copy the code

Set side effects (even unreferenced code can participate in packaging)

In production mode, the webpack.config.js file is automatically set to remove invalid code without side effects

Enable side effect packaging in other modes

module.exports->{ optimization }->{ sideEffects: true }
Copy the code

** Set side effects: ** Set them in webpack.json

{... ."sideEffects": [
// Write the file path with side effects in the array
    "./src/extend.js"."*.css"]}Copy the code

The code segment

After WebPack is packaged, the code (modules) is concentrated in a SINGLE JS file. To make it easier to run your code, you can package and generate multiple JS files, using the corresponding files as needed

Split packaging: multi-entry packaging, dynamic import

Multiple entry packing

Setting method:

const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  mode: 'none'.entry: {
    // Set up different package entry, note: this must be in object mode
    index: './src/index.js'.album: './src/album.js'
  },
  output: {
    // Set the output file thing
    filename: '[name].bundle.js'
  },
  module: {
    rules: [......]. },plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: 'Multi Entry'.template: './src/index.html'.filename: 'index.html'.// Build the HTML file for the first entry
      chunks: ['index']}),new HtmlWebpackPlugin({
      title: 'Multi Entry'.template: './src/album.html'.filename: 'album.html'.// Build the HTML file for the second entry
      chunks: ['album']]}})Copy the code

There is an obvious problem with this setup: some common modules can be packaged multiple times, so simply add the optimization property to the WebPack configuration file and set splitChunks:{chunks:true}

module.exports = { 
    optimization: {
    splitChunks: {
      // Automatically extract all public modules into separate bundles
      chunks: 'all'}}Copy the code

Dynamic import

Essentially load on demand, load only what you need

This method needs to be set in the js file under development

const render = () = > {
  const hash = window.location.hash || '#posts'
  const mainElement = document.querySelector('.main')
  mainElement.innerHTML = ' '
  if (hash === '#posts') {
    // mainElement.appendChild(posts())
    import(/* webpackChunkName: 'components' */'./posts/posts').then(({ default: posts }) = > {
      mainElement.appendChild(posts())
    })
  } else if (hash === '#album') {
    // mainElement.appendChild(album())
    import(/* webpackChunkName: 'components' */'./album/album').then(({ default: album }) = > {
      mainElement.appendChild(album())
    })
  }
}

render()

window.addEventListener('hashchange', render)
Copy the code

MiniCssExtractPlugin

Package CSS files as a single CSS file instead of rendering them from JS files (it is recommended to use CSS files over 150KB, otherwise multiple requests will be made)

Plug-in required: Mini-CSS-extract-plugin

Usage: Used in configuration files

const MiniCssExtractPlugin = require('mini-css-extract-plugin')

module.exports = {
    module: {
    rules: [{test: /\.css$/,
        use: [
         / / change the CSS - loader to MimiCssExtractPlugin. Loader
          MiniCssExtractPlugin.loader,
          'css-loader'}]}}Copy the code

But the resulting file is not compressed

To do this, you need a special plugin optimization-cssassets-webpack-plugin to compress CSS files

const MiniCssExtractPlugin = require('mini-css-extract-plugin')
/ / CSS compression
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')
/ / js compressed
const TerserWebpackPlugin = require('terser-webpack-plugin')

module.exports = {
  optimization: {
    minimizer: [
     // Set the compression loader
     // Note: when setting the compression, the original JS compression will be overwritten, so use the original JS compression to write
     // js compressed to erser-webpack-plugin
      new TerserWebpackPlugin(),
      new OptimizeCssAssetsWebpackPlugin()
    ]
  },
  module: {
    rules: [{test: /\.css$/,
        use: [
          // 'style-loader', // inject the style through the style tag
          MiniCssExtractPlugin.loader,
          'css-loader']]}},plugins: [
    new CleanWebpackPlugin(),
    // Compress the file
    new MiniCssExtractPlugin()
  ]
}
Copy the code