Problems with using modularity:

There are environmental compatibility problems in ES Module, especially in the lovely IE. 2. Too many Module files and frequent network requests

Chapter 1: Introduction to Webpack

1.1 What is Webpack

Webpack is a front-end resource builder, a static Module bundler.

In webpack’s view, all the front-end resource files (JS /json/ CSS /img/less/…) Will be treated as modules.

It will carry out static analysis according to module dependencies and generate corresponding static resources (bundles).

1.2 Five core concepts of Webpack

1.2.1 Entry

The Entry indicates which file webPack starts packing as the Entry point, analyzing and building the internal dependency diagram.

1.2.2 the Output

Output indicates where the resource bundles Output from WebPack go and how to name them.

1.2.3 Loader

Loader allows Webpack to handle non-javascript files (Webpack only handles JavaScript itself)

1. The Plugins

Plugins can be used to perform a much wider range of tasks. Plug-ins range from packaging optimization and compression to redefining variables in the environment.

1.2.5 Mode

Mode instructs Webpack to use the configuration of the corresponding Mode

Development mode, production mode

Chapter 2: The first taste of Webpack

2.1 Initial Configuration

Initialize package.json

Create a new folder, use an editor such as vscode, open the folder and type NPM init on the command line of the editor

2. Download and install webPack

From the command line in edit, type the command: NPM install webpack webpack-cli -g NPM install webpack webpack-cli –save-dev [=]

2.2 Compiling and Packaging Applications

1. Create a file

Create a directory named build and a directory named SRC in the 2.1 folder. Create a file named index.js in the SRC directory and the code inside the file is as follows:

function add (x, y) {
  return x + y
}
console.log(add(1, 2))
Copy the code

2. Run directives (no global installation of Webpack)

NPX webpack. / SRC /index.js -o./build –mode=development will eventually generate a packed main.js file in the build directory

/ SRC /index.js and output to./build/built. The overall package environment is the development environment

Features: WebPack compiles packaged JS and JSON files and converts es6’s modular syntax into a syntax that browsers can recognize.

NPX webpack. / SRC /index.js -o./build –mode=production Will eventually generate a packed main.js file in the build directory. The code inside will be compressed

/ SRC /index.js and output to./build/built. The overall packaging environment is the production environment

2, function: in the development of configuration function on a function, compression code.

Conclusion 3.

(1) Webpack can compile packaged JS and JSON files. (2) It can convert es6’s modular syntax into a syntax that the browser can recognize. (3) The production environment can compress code.

Problem 4.

(1) Cannot compile and package CSS, IMG and other files. (2) Js basic es6 syntax cannot be converted to es5 syntax.

Chapter 3: Basic configuration of the WebPack development environment

3.1 Creating a Configuration File

1. Create the webpack.config.js file

2. Set the parameters as follows

const { resolve } = require('path'); // Node has a built-in core module to handle path problems. Module.exports = {entry: './ SRC /index.js', // exports file output: {// exports filename: './ build.js ', // exports file path: Resolve (__dirname, 'build') // output file path configuration}, mode: 'development' // development environment};Copy the code

3. Run the command: NPX webpack

4. Conclusion: This function is the same as the previous section

3.2 Packaging style resources

1. Create a file

2. Download and install the Loader

npm install –save-dev css-loader style-loader less-loader less

3. Modify the webpack.config.js configuration file

Const {resolve} = require('path'); Module.exports = {// webpack configuration // entry entry: './ SRC /index.js', // output: {// output filename: 'build.js ', // output path // __dirname nodejs variable, representing the absolute path of the current file directory path: resolve(__dirname, 'build')}, // Loader configuration module: {rules: [// detailed loader configuration // Different files must be configured for different loader processing {// which files match test: /\.css$/, // Which loaders are used for processing use: [// use the order of loader execution in array: Create style tags from right to left, from bottom to top, insert style resources in JS, add to head 'style-loader', // change CSS file into commonJS module to load js, }, {test: /\. Less $/, use: ['style-loader', 'css-loader', // to compile less files into CSS files // less 'less-loader' and less 'less-loader']}]}, Plugins: [// detailed plugins], // mode: 'development', // mode: 'production'}Copy the code

4. Run the command: NPX webpack

If the following error occurs, it indicates that the version of CSS-Loader, style-loader, and less-loader is too old. If you change the version to a later version, you can pack normally

3.3 Packaging HTML Resources

1. Create a file

2. Download the Plugin package

npm install –save-dev html-webpack-plugin

3. Modify the webpack.config.js configuration file

const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { filename: 'built.js', path: Resolve (__dirname, 'build')}, module: {rules: [// loader configuration]}, plugins: [// plugins // html-webpack-plugin // functions: create an empty HTML by default, automatically import all the resources (JS/CSS) packaged output // requirements: New HtmlWebpackPlugin({// copy the './ SRC /index.html' file and automatically import all the resources (JS/CSS) that package the output: './src/index.html' }) ], mode: 'development' };Copy the code

4. Run the command: NPX webpack

3.4 Packaging Image Resources

1. Create a file

2. Download and install the Loader

npm install –save-dev html-loader url-loader file-loader

3. Modify the webpack.config.js configuration file

const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { filename: 'built.js', path: Resolve (__dirname, 'build')}, module: {rules: [{test: /\. Less $/, // ['style-loader', 'css-loader', 'less-loader']}, {// <img SRC ="./angular.jpg" Alt ="angular"> / \. (JPG | PNG | GIF) $/, / / the use of a loader / / download url - loader file - loader loader: 'url - loader, the options: {// Image size less than 8KB, will be base64 processing // advantages: reduce the number of requests (reduce server stress) // disadvantages: larger image size (slower file request) limit: [object Module] [object Module] // Resolve: // esModule: {// esModule: false} False, // Rename the image // [hash:10] take the first 10 bits of the hash of the image // [ext] Take the original file extension name: '[hash:10].[ext]'}}, {test: <img SRC ="./angular.jpg" Alt ="angular"> 'html-loader' } ] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }) ], mode: 'development' };Copy the code

4. Run the command: NPX webpack

3.5 Packing Other Resources

1. Create a file

2. Modify the configuration file

const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { filename: 'built.js', path: resolve(__dirname, 'build') }, module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader']}, // Use file-loader {// exclude CSS /js/ HTML resources; // exclude CSS /js/ HTML resources: /\.(css|js|html|less)$/, loader: 'file-loader', options: { name: '[hash:10].[ext]' } } ] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }) ], mode: 'development' };Copy the code

3. Run the command: NPX webpack

3.6 devserver

1. Create a file

The same as the 3-5 package files for other resources

2. Download and install the WebPack-EV-server package

npm install –save-dev webpack-dev-server

3. Modify the configuration file

2, Webpack-dev-server will only compile and pack in memory, and will not produce any output

const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { filename: 'built.js', path: resolve(__dirname, 'build') }, module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader']}, // Use file-loader {// exclude CSS /js/ HTML resources; // exclude CSS /js/ HTML resources: /\.(css|js|html|less)$/, loader: 'file-loader', options: { name: '[hash:10].[ext]' } } ] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }) ], mode: 'development', // devServer: used for automation (automatic monitoring, automatic compilation, automatic opening of the browser, automatic refreshing of the browser ~~) // Features: only compile packages in memory, no output // devServer startup command is: NPX webpack-dev-server devServer: {contentBase: resolve(__dirname, 'build'), // gzip compress: True, // Port: 4000, // automatically open the browser open: true}};Copy the code

4. Run command: NPX webpack-dev-server

3.7 Basic Configuration of the development environment (a tidy up of all the above)

1. Create a file

2. Download NPM install –save-dev package name

“CSS – loader”, “^ 3.6.0”, “file – loader” : “^ 6.2.0”, “HTML – loader” : “^ 1.3.2”, “HTML – webpack – plugin” : “^ 4.5.0”, “less” : “^ 2.7.3,” “less – loader” : “^ 5.0.0”, “style – loader” : “^ 1.3.0”, “url – loader” : “^ 4.4.1”, “webpack” : “^ 4.26.1 webpack -“, “cli” : “^ 3.3.12”, “webpack – dev – server” : “^ 3.11.0”

3. Modify the configuration file

Exports = {// project entry: // project entry: // project entry: // project entry: // project entry: // project entry: // project entry: './ SRC /js/index.js', // project exit output: {filename: 'js/ built-in ', // generated the corresponding entry js file path: Path. join(__dirname, 'built')}, // Corresponding loager module: {rules: [// loader {test: /\.css$/, use: ['style-loader', 'css-loader']}, // loader to handle less {test: /\. Less $/, use: ['style-loader', 'css-loader', 'less-loader']}, // Loader to handle images, // But url-loader cannot handle images referenced by img tags in HTML files, With HTML - loader is needed to deal with {test: / \. (PNG | JPG | GIF) $/, loader: 'url - loader' options: {limit: 8 * 1024, // Image < 8KB base64 encoding, output to build.js outputPath: 'images', // image file packaged and saved in build/images/ name: '[hash:10].[ext]'}}, // Loader to handle images, // But urL-loader can't handle images referenced by the IMG tag in HTML files, use htMl-loader to handle {test: $/, / \. HTML loader: 'HTML - loader'}, / / handle other types of file loader {exclude: / \ | | js | (HTML CSS less | JPG | PNG | GIF) /, loader: 'file-loader', options: {outputPath: 'public', // Save other files in build/public/ '[hash:10].[ext]' // The packaged file name shows the 10-bit hash value}}]}, // corresponding to the plugins plugins: New HtmlWebpackPlugin({template: './ SRC /index.html'})], // Mode: 'development', // mode:'production' devServer: { open: true, compress: true, port: 400, contentBase: path.join(__dirname, 'build') } }Copy the code

4. Run NPX webpack and NPX webpack-dev-server to see the effect

Chapter 4: Basic configuration of the WebPack production environment

4.1 Extracting the CSS into a separate file

1. Create a file

2. Download the plug-in

npm install –save-dev mini-css-extract-plugin

3. Modify the configuration file

const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') const miniCssExtractPlugin = require('mini-css-extract-plugin') module.exports = { entry: './src/js/index.js', output: { filename: 'build/js/built.js', path: path.join(__dirname, 'build') }, module: { rules: [ { test: /\.css$/, use: [// create style tag, put style in // 'style-loader', // this loader replaces style-loader. Extract the CSS into individual files in the js MiniCssExtractPlugin. Loader, / / to integrate the CSS file and js file 'CSS - loader]}}], plugins: [new HtmlWebpackPlugin({template: './ SRC /index.html'}), new miniCssExtractPlugin({// Rename the output CSS file filename: 'build/css/built.css' }) ], mode: 'development' }Copy the code

4. Run the command: NPX webpack

4.2 CSS Compatibility

1. Create a file

2. Download the plug-in

npm install –save-dev postcss-loader postcss-preset-env

3. Modify the configuration file

const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); // browserslist If you want to use the development environment, you need to set the node environment variable // process.env.node_env = 'development'; module.exports = { entry: './src/js/index.js', output: { filename: 'js/built.js', path: resolve(__dirname, 'build') }, module: { rules: [ { test: /\.css$/, use: [MiniCssExtractPlugin. Loader, 'CSS - loader, / * CSS compatibility processing need to download the plugin: Postcss-loader postCSs-preset -env postCSs-preset -env Find browserslist configuration in package.json for postCSs-loader Browserslist can be used to search for the package name browserslist. By default, browserslist goes to the production environment. If you want to use the development environment, you need to set the Node environment variable "browserslist": {// development environment --> Set the node environment variable: process.env.node_env = development" development": ["last 1 Chrome version", "last 1 Firefox version", "last 1 Safari version"], // Production environment: default is to look at the production environment "production": [">0.2%", "not dead", "not op_mini all"]} */ / Use default loader configuration // 'postcss-loader', // Modify loader configuration { 'postcss-loader', options: { ident: 'postcss', plugins: () => [// postCSS require(' postCSs-env ')()]}}]}]}, plugins: [new HtmlWebpackPlugin({template: preset) './src/index.html' }), new MiniCssExtractPlugin({ filename: 'css/built.css' }) ], mode: 'development' };Copy the code

4. Modify the package. Json

"browserslist": { "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ], "production": [">0.2 ", "not dead", "not op_mini all"]}Copy the code

5. Run the command: NPX webpack

4.3 compressed CSS

1. Create a file

2. Download the plug-in

npm install –save-dev optimize-css-assets-webpack-plugin

3. Modify the webpack.config.js configuration file

Add reference of the head plug-in const OptimizeCssAssetsWebpackPlugin = the require (' optimize - CSS - assets - webpack - plugin ') is added in the plugins array using the plugins:  [ new HtmlWebpackPlugin({ template: './src/index.html' }), new MiniCssExtractPlugin({ filename: 'CSS/built. CSS'}), / / used here: compress CSS new OptimizeCssAssetsWebpackPlugin ()],Copy the code

4. Run the command: NPX webpack

4.4 JS Syntax Check

1. Create a file

2. Download the plug-in

npm install –save-dev eslint-loader eslint eslint-config-airbnb-base eslint-plugin-import

3. Modify the webpack.config.js configuration file

const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/js/index.js', output: { filename: 'js/built.js', path: resolve(__dirname, 'build') }, module: { rules: [/* Eslint-loader: eslint-loader: eslint-loader: eslint-loader: eslint-loader: eslint-loader: eslint-loader: eslint-loader { "extends": "Airbnb -base"} Eslint-config-airbnb-base eslint-plugin-import eslint eslint-config-airbnb-base is a style of syntax checking for eslint */ {test: /\.js$/, exclude: /node_modules/, // }}, plugins: [new HtmlWebpackPlugin({template: './ SRC /index.html'})], mode: 'development' };Copy the code

4. The configuration package. Json

"eslintConfig": {
    "extends": "airbnb-base",
    "env": {
    "browser": true
    }
}

Copy the code

5. Run the command: NPX webpack

4.5 JS compatibility handling (converting es6 or ES6 + syntax into ES5 syntax that browser can recognize)

1. Create a file

2. Download the plug-in

npm install –save-dev babel-loader @babel/core @babel/preset-env @babel/polyfill core-js

3. Modify the webpack.config.js configuration file

const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/js/index.js', output: { filename: 'js/built.js', path: resolve(__dirname, 'build') }, module: { rules: [/* PRESET: babel-loader @babel/core 1. Basic JS compatibility --> @babel/preset-env 2. All js compatibility processing --> @babel/polyfill does not need to configure, directly in the JS file can be introduced problem: */ {test: */ {test: */ {test: */ {test: */ {test: */ /\.js$/, exclude: /node_modules/, // exclude: /node_modules/, // exclude: /node_modules/ / [['@babel/preset-env', {// Load useBuiltIns as needed: 'usage', // Specify core-JS version corejs: {version: Targets: {Chrome: '60', Firefox: '60', IE: '9', Safari: '10', edge: '17' } } ] ] } } ] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }) ], mode: 'development' };Copy the code

4. Run the command: NPX webpack

4.6JS compression (in production, just set mode to production)

1. Create a file

2. Download the plug-in

3. Modify the webpack.config.js configuration file

const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/js/index.js', output: { filename: 'js/built.js', path: resolve(__dirname, 'build') }, plugins: [ new HtmlWebpackPlugin({ template: './ SRC /index.html'})], // The production environment will automatically compress js code // just set mode to production mode: 'production'};Copy the code

4. Run the command: NPX webpack

4.7 HTML compression

1. Create a file

2. Download the plug-in

npm install –save-dev html-webpack-plugin

3. Modify the webpack.config.js configuration file

const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/js/index.js', output: { filename: 'js/built.js', path: Resolve (__dirname, 'build')}, plugins: [new HtmlWebpackPlugin({template: './ SRC /index.html', // minify: CollapseWhitespace: true, // Collapse comment removeComments: true}})], mode: 'production'};Copy the code

4. Run the command: NPX webpack

4.8 Basic Configuration of the Production Environment (Tidy up all the above contents)

1. Create a file

2. Download NPM install –save-dev package name

“@ Babel/core”, “^ 7.12.9”, “@ Babel/preset – env” : “^ 7.12.7”, “Babel – loader” : “^ 8.2.1”, “core – js” : “^ 3.7.0”, “CSS – loader” : “^ 5.0.1 eslint”, “”,” ^ 7.14.0 “, “eslint – config – reality – base”, “^ 14.2.1”, “eslint – loader” : “^ 4.0.2 eslint”, “- the plugin – import” : “^ 2.22.1”, “file – loader” : “^ 6.2.0”, “HTML – loader” : “^ 1.3.2”, “HTML – webpack – plugin” : “^ 4.5.0” and “less”, “^ 3.12.2”, “less – loader” : “^ 7.1.0”, “mini – CSS – extract – the plugin” : “^ 1.3.1”, “optimize – CSS – assets – webpack – plugin” : “^ 5.0.4”, “postcss – loader” : “^ 3.0.0”, “postcss – preset – env” : “^ 6.7.0”, “url – loader” : “^ 4.4.1”, “webpack” : “^ 4.44.2”, “webpack – cli” : “^ 3.3.12”

3. Modify the webpack.config.js configuration file

const path = require('path') const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); // Define the nodejs environment variable: decide which environment to use browserslist. The default is production. / / reuse loader const commonCssLoader = [MiniCssExtractPlugin loader, 'CSS - loader, Loader: 'postcss-loader', options: {ident: 'postcss', plugins: () => [require('postcss-preset-env')()] } } ]; Module.exports = {// exports entry: './ SRC /js/index.js', // export: {filename: Path: path.join(__dirname, 'build') // File input directory}, // loader module: {rules: [/ / processing of CSS loader / / CSS code as a separate file out within js file after packaging: MiniCssExtractPlugin. Loader / / // Optimize - CSS-assets -webpack-plugin {test: preset (); // Optimize - CSS-assets -webpack-plugin {test: preset (); /\.css$/, use: [...commonCssLoader]}, // Handle less loader: less-loader {test: /\.less$/, use: [...commonCssLoader, 'less-loader']}, /** * Normally, a file can only be processed by one loader. // / add a new property to Babel: // Check the syntax of js (eslint, eslint-loader, eslint-config-Airbnb -base, eslint-plugin-import) // Check the compatibility of JS (babel-loader, @babel/core, {// In package.json eslintConfig --> Airbnb test: // Preset -- env, core-js) // PRESET -- compression of JS code (mode mode) // JAVASCRIPT syntax check {// eslintConfig --> Airbnb test: /\.js$/, exclude: /node_modules/, enforce: 'pre', // loader: 'eslint-loader', options: {fix: {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', options: { presets: [ [ '@babel/preset-env', { useBuiltIns: 'usage', corejs: { version: 3 }, targets: { chrome: '60', firefox: '50'}}}}]], / / image processing loader plugin url - loader {test: / \. (JPG | PNG | GIF) /, the loader: 'url - loader' options: {limit: 8 * 1024, name: '[hash:10].[ext]', outputPath: 'images', / / picture save position}} after packaging, / / handle other file type loader plugin file - loader {exclude: / \. (js | | CSS less | | HTML JPG | PNG | GIF) /, loader: 'file-loader', // output options: {outputPath: 'public', name: '[hash:10].[ext]'}}, // Handle image path from img tag in HTML file. /\.html$/, loader: 'html-loader' }, ] }, // plugins plugins: New MiniCssExtractPlugin({filename: 'CSS/built. CSS / /} a separate CSS file storage locations), / / to compress the CSS file new OptimizeCssAssetsWebpackPlugin (), New HtmlWebpackPlugin({// Create a new file template: './ SRC /index.html' in the build directory, // compress the HTML file minify: CollapseWhitespace: true, collapseecomments: true})], collapseWhitespace: true, collapseecomments: true}Copy the code

Modify the package.json file

"browserslist": { "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ], "production": [" > 0.2%, "" not op_mini all"]}, "eslintConfig" : {" extends ": // eslint does not know window/navigator global variables // eslintConfig config: package.json; // eslintConfig: {"browser": true/supports browser-side global variables}}Copy the code

6. Run the command: NPX webpack

Chapter 5: WebPack optimization configuration

5.1 HMR – DevServer-based, so HMR cannot be used in production environments

1. The problem

In development mode, after devServer is started, a file changes and all files need to be repackaged, which is time-consuming

2. HMR: Hot module replacement

What it does: When a module changes, it repackages only that module (not all modules), greatly increasing build speed

Style files: you can use the HMR function: because style-loader implements ~ internally

Note: the HMR function can only handle other files that are not entry JS files.

HTML files: the HMR function is disabled by default. At the same time, there are problems: THE HTML file cannot be hot updated ~ (do not need to do HMR function) Solution: Modify the entry entry to import the HTML file

3. Modify entry and devServer configurations in webpack.config.js

entry: ['./src/js/index.js', './src/index.html'], devServer: { contentBase: resolve(__dirname, 'build'), compress: Hot: true, port: 3000, open: true, // Enable the HMR function // When modifying the webPack configuration, the new configuration must be restarted to take effect.Copy the code

4. Js file cannot use HMR function by default –> Need to modify the code in js file, the code is as follows

The contents of the print.js file

function print() {
  const content = 'hello print';
  console.log(content);
}

export default print;

Copy the code

The contents of the index.js file

// Import print from './print'; print(); If (module.hot) {// If module.hot is true, HMR is enabled. Module.hot.accept ('./print.js', function() {// the method listens for changes in print.js. The print.js file will be reloaded // but other modules will not be repackaged to build print(); }); }Copy the code

5.2 the source – the map

1. What is source-map?

Is a technique that provides source-to-build code mapping (mapping to trace source code errors if they occur after a build)

2. What types of source-map can be configured?

[inline-|hidden-|eval-][nosources-][cheap-[module-]]source-map

  • Source-map: external

—- displays accurate information about the error code and the exact error location of the source code

  • 2, inline-source-map: inline

—– generates only an inline source-map —– that shows the exact information of the error code and the exact error location of the source code

  • Hidden-source-map: external

—– can display the exact information of the error code, but can not display the error location of the source code —– can not trace the error source code, only prompt to the error location of the built code

  • Eval-source-map: inline

—– Each file generates a corresponding source-map, which —– can display in eval the exact information of the error code and the exact error location of the source code

  • 5. Nosource-source-map: external

—– displays accurate information about the error code, but does not find any corresponding source information

  • 6. Cheap -source-map: external

—– can display the exact information of the error code and the exact error location of the source code —– can only be accurate to the line

  • 7, cheap-module-source-map: external

—– displays accurate information about the error code and the exact error location of the source code —– Module adds the Source map of the Loader

  • 8. The difference between inline and external:

—–1. Files are generated externally, but not inline. 2

  • 9. Choose SouCE-Map for development environment: Souce-Map is faster and more friendly for debugging

—– fast (eval>inline>cheap>…) — — — — — — — the eval – being – souce map — — — — — — — the eval – source – the map debug more friendly — — — — — – — — — — — – souce – map — — — — — — — being the module – souce – map ——-cheap-souce-map

  • 10. Final choice of development environment SouCE-Map:

—–eval-source-map / eval-cheap-module-souce-map

  • Choose Souce-Map for production environment: Should source code be hidden or not? Should debugging be friendlier?

——- inlining will make the code larger, so in the production environment do not inline ——- nosource-source-map all hidden ——-hidden-source-map only hides the source code, which will prompt an error message after the build

  • 12. Final selection of production environment SouCE-Map [for more debug friendly purposes] :

——source-map / cheap-module-souce-map

3. Modify the webpack.config.js configuration file

devtool: 'eval-source-map'devServer: { contentBase: resolve(__dirname, 'build'), compress: true, port: 3000, open: True, hot: true // enable HMR function}, devtool: 'source-map' //Copy the code

5.3 oneOf – Used in production environment, not necessary in development environment

1. What is oneOf used for?

OneOf is used to speed up the packaging of builds. OneOf is used to process loaders in webPack configuration. OneOf only matches one loader

2. Modify the webpack.config.js configuration file

// loader module: { rules: OneOf can't have two loaders handling the same type of file. OneOf can't have two loaders handling the same type of file. OneOf can't have two loaders handling the same type of file {// in package.json eslintConfig --> Airbnb test: /\.js$/, exclude: /node_modules/, enforce: 'pre', // loader: 'eslint-loader', options: {fix: }}, // oneOf is wrapped in an object, oneOf itself passes an array, OneOf: {oneOf: [// loaders for CSS {test: /\.css$/, use: [...commonCssLoader]}, // Handle less loader: less-loader {test: /\. Less $/, use: [...commonCssLoader, 'less-loader']}, exclude: // node_modules/, exclude: // node_modules/ 'babel-loader', options: { presets: [ [ '@babel/preset-env', { useBuiltIns: 'usage', corejs: { version: 3 }, targets: { chrome: '60', firefox: '50' } } ] ] } } ] } ] },Copy the code

5.4 the cache

The caching time is set on the server, and the WebPack configuration file can be set to enable caching

1. Babel cache – Modify the configuration file webpack.config.js

// loader module: {rules: [// js compatibility {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', options: { presets: [ [ '@babel/preset-env', { useBuiltIns: 'usage', corejs: { version: 3 }, targets: { chrome: '60', firefox: CacheDirectory: true}}]}, cacheDirectory: true}}]},Copy the code

2. File resource cache – Modify the configuration file webpack.config.js

(1) Hash: each wepack build will generate a unique hash value.

Problem: If webpack is repackaged, new hash values will be generated, invalidating all file caches (e.g., I only modify one file)

(2) Chunkhash: indicates the hash value generated by chunk. If the package comes from the same chunk, the hash value is the same

Problem: JS and CSS have the same hash value because CSS is introduced in JS, so it belongs to the same chunk

Contenthash: Generates hash values based on the contents of files. Different files must have different hash values

Can make code run online cache better use

(4) Modify the configuration file webpack.config.js
Module. exports = {output: {// File resource cache core configuration location: use contenthash filename: 'js/built.[contenthash:10].js', path: Resolve (__dirname, 'build')}, plugins: [new MiniCssExtractPlugin({contenthash filename: 'css/built.[contenthash:10].css' }) ], };Copy the code

5.5 Tree shaking

1. Tree shaking: Remove useless code

Prerequisites: 1. ES6 modularization must be used. 2

2. Configure it in package.json

“sideEffects”: False All code is tree shaking with no side effects. Tree shaking in some webpack versions may dry out CSS / @babel/polyfill files

SideEffects: [“.css”, “.less”]

5.6 Code split (code split into multiple separate files)

Code split is mainly used to split THE JS code

1. Code split method one => modify the configuration file webpack.config.js

const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); Module.exports = {// single entry // entry: './ SRC /js/index.js', entry: {// multiple entries: one entry, the final output has a bundle index: './ SRC /js/index.js', test: './ SRC /js/test.js'}, output: {// [name] : selects the filename corresponding to the key in the entry filename: 'js/[name].[contenthash:10].js', path: resolve(__dirname, 'build') }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html', minify: { collapseWhitespace: true, removeComments: true } }) ], mode: 'production' };Copy the code

2. Code split method 2 => modify the configuration file webpack.config.js

const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); Module.exports = {// single entry // entry: './ SRC /js/index.js', entry: {index: './ SRC /js/index.js', test: './ SRC /js/test.js'}, output: {// [name] : select filename: 'js/[name].[contenthash:10].js', path: resolve(__dirname, 'build') }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html', minify: { collapseWhitespace: true, removeComments: true } }) ], /* 1. Node_modules can be packaged as a separate chunk of code and output 2. Automatic analysis of multi-entry chunks, whether there are public files. */ chunks: {splitChunks: {chunks: 'all'}} mode: 'production'};Copy the code

3. Code split =>import dynamic import syntax

(1) Modify the configuration file webpack.config.js
const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); Module.exports = {// single entry: './ SRC /js/index.js', plugins: [new HtmlWebpackPlugin({template: './src/index.html', minify: { collapseWhitespace: true, removeComments: true } }) ], /* 1. Node_modules can be packaged as a separate chunk of code and output 2. Automatic analysis of multi-entry chunks, whether there are public files. */ chunks: {splitChunks: {chunks: 'all'}} mode: 'production'};Copy the code
(2) modify the code in the JS file

In the index.js file, using the import dynamic import syntax, the test.js file is imported and the methods exposed in test.js can be used in the index.js file while webpack generates 2 separate JS files

Contents of the index.js file

function sum(... args) { return args.reduce((p, c) => p + c, 0); } console.log(sum(1, 2, 3, 4)); /* webpackChunkName: /* webpackChunkName: /* webpackChunkName: 'test' */'./test' changes the packaged file name to test */ import(/* webpackChunkName: 'test' * '/ test'), then (({count} the mul,) = > {/ / file loaded successfully to the console. The log (the mul (2, 5)); }).catch(() => {console.log(' file failed to load ~'); });Copy the code

Contents of the test.js file


export function mul(x, y) {
  return x * y;
}

export function count(x, y) {
  return x - y;
}

Copy the code

5.7 Lazy Loading (Lazy loading of JS files)

  • Lazy loading: files are loaded when they are needed
  • Preloading: loads js files in advance before use
  • Normal loading can be considered parallel loading (loading multiple files at the same time)
  • Preload: Surreptitiously load resources when other resources are loaded and the browser is idle
  • Pre-loaded browsers, such as Internet Explorer, may have compatibility problems
  • Lazy loading can be seen as the same as the code split method three =>import dynamic import syntax

1. Configure the webpack.config.js file

const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); Module.exports = {// single entry: './ SRC /js/index.js', output: {filename: 'js/[name].[contenthash:10].js', path: resolve(__dirname, 'build') }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html', minify: { collapseWhitespace: true, removeComments: true } }) ], optimization: { splitChunks: { chunks: 'all' } }, mode: 'production' };Copy the code

2. Contents of the index.js file

Console. log('index.js file loaded ~'); // import { mul } from './test'; Document.getelementbyid (' BTN ').onclick = function() webpackChunkName: 'test', webpackPrefetch: true */'./test').then(({ mul }) => { console.log(mul(4, 5)); }); };Copy the code

3. Contents of the test.js file

Console. log('test.js file was loaded ~'); export function mul(x, y) { return x * y; } export function count(x, y) { return x - y; }Copy the code

4. The contents of the index.html file

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, > <title>webpack</title> </head> <body> <h1> Hello lazy loading</h1> <button id=" BTN "> </body> </html>Copy the code

5.8 PWA

5.9 Multi-process Packaging

Mainly for JS compatibility processing loader [babel-loader] to use

1. Download the installation package

npm install –save-dev thread-loader

2. Modify the webpack.config.js configuration file

// loader module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: [/* enable multi-process packaging. The process startup takes about 600ms, and the process communication costs too much. {workers: 2 // 2 processes}}, {loader: 'babel-loader', options: {workers: 2 processes}}, {loader: 'babel-loader', options: { presets: [ [ '@babel/preset-env', { useBuiltIns: 'usage', corejs: { version: 3 }, targets: { chrome: '60', firefox: '50'}}]], // enable Babel cache // on the second build, the previous cache will be read cacheDirectory: true}}]}]}Copy the code

5.10 externals (reject third-party packages that can be referenced by CDN)

1. Modify the webpack.config.js configuration file

Externals: {// reject jQuery to be packaged in jQuery: 'jQuery'}Copy the code

5.10 DLL => Dynamic link library

1. Create a webpack.dll.js file in the root directory of the project

2. Modify the webpack.dll.js configuration file

/* Use DLL technology for some libraries (third-party libraries: jquery, React, vue...) When you run webpack, the default is to look for the webpack.config.js configuration file. npx webpack --config webpack.dll.js */ const { resolve } = require('path'); const webpack = require('webpack'); Module. exports = {entry: {// ['jquery'] --> jquery // ['jquery'] --> {filename: '[name].js', path: resolve(__dirname, 'DLL '), Library: '[name]_[hash]'}, plugins: New webpack.DllPlugin({name: '[name]_[hash]', // Map library exposed content name path: Resolve (__dirname, 'DLL /manifest.json') // output file path})], mode: 'production'};Copy the code

3. Run the NPX webpack –config webpack.dl.js command

DLL folders are generated, which contain the corresponding packaged files

4. Download the plug-in

npm install –save-dev add-asset-html-webpack-plugin

5. Modify the webpack.config.js configuration file

const { resolve } = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') const webpack = Require (' webpack ') / / modify here const AddAssetHtmlWebpackPlugin = the require (' add - asset - HTML - webpack - plugin ') / / modify here module.exports = { entry: './src/index.js', output: { filename: 'built.js', path: resolve(__dirname, 'build') }, plugins: [ new HtmlWebpackPlugin({ template: ' '. / SRC/index. HTML}), / / / / modify here tell webpack which libraries don't participate in the packaging, use at the same time also have to change the name of the new webpack. DllReferencePlugin ({manifest: Resolve (__dirname, 'DLL /manifest.json')}), And in HTML automatically is introduced into the resources of new AddAssetHtmlWebpackPlugin ({filepath: resolve (__dirname, 'the DLL/jquery. Js)})], mode: 'production' }Copy the code

5.11 Differences between Externals and DLLS

Externals 1. You only need to configure this parameter in the webpack.config.js file

2. Reject third-party packages and package them in. These packages can be referenced in the HTML page after package by CDN

DLL (dynamic link library) 1, need to write their own manual configuration code to package, the implementation of trouble, only need to package a can

2, Use DLL technology, some libraries (third-party libraries: jquery, React, vue…) Pack separately

3. It also needs to be configured in the webpack.config.js file

5.12 A simple summary of WebPack performance optimization

Webpack performance optimization

  • Development environment performance optimization
  • Production environment performance optimization

Development environment performance optimization

  • Optimize packaging build speed
    • HMR
  • Optimized code debugging
    • source-map

Production environment performance optimization

  • Optimize packaging build speed
    • oneOf
    • Babel cache
    • Multi-process packaging
    • externals
    • dll
  • Optimize the performance of code execution
    • Cache files (Hash, chunkhash, contenthash)
    • tree shaking
    • code split
    • Lazy loading/preloading
    • PWA

Chapter 6: WebPack configuration details

6.1 entry

Entry: Several ways of writing the starting point of an entry
1. string –> ‘./src/index.js’
  • Single entry
  • Pack up to form a chunk. Output a bundle file.
  • The default name of chunk is main
2. array –> [‘./src/index.js’, ‘./src/add.js’]
  • Multiple entry
  • All the import files end up as a chunk, and only one bundle is exported.
  • Commonly used to process, in the HMR function to enable HTML hot updates
3. object
  • Multiple entry
  • Several import files form several chunks and export several bundles
  • The name of chunk is key
4. Special usage
{// All incoming files end up as a chunk, and only one bundle is exported. Index: ['./ SRC /index.js', './ SRC /count.js'], // form a chunk and output a bundle file. add: './src/add.js' }Copy the code

6.2 the output

const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); Module. exports = {entry: './ SRC /index.js', output: {// filename: 'js/[name].js', // output file directory (public directory for future output of all resources) path: resolve(__dirname, 'build'), / / all resources into public path prefix -- > 'imgs/a. pg' - > '/ imgs/a. pg / / < img SRC = "imgs/a. pg" / > -- > < img SRC = "/ imgs/a. pg" / > publicPath: '/', // usually used in production mode chunkFilename: 'js/[name]_chunk.js', // Name of non-entry chunk // library: '[name]', // the variable name exposed by the entire library // libraryTarget: 'window' // which variable name is added to browser // libraryTarget: 'global' // which node to add variable names to // libraryTarget: 'commonJS' // expose libraries externally with commonJS specification}, plugins: [new HtmlWebpackPlugin()], mode: 'development' }Copy the code

6.3 the module

const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { filename: 'js/[name].js', path: Resolve (__dirname, 'build')}, module: {rules: [// loader configuration {test: /\.css$/, // ['style-loader', 'css-loader']}, {test: /\.js$/, // exclude the js file under node_modules: Include: resolve(__dirname, 'SRC '), // enforce: 'pre' first, // defer: // enforce: 'pre' 'post', // single loader uses loader: 'eslint-loader', // loader corresponding configuration options options: {}}, {// The following configuration will only take effect oneOf: [] } ] }, plugins: [new HtmlWebpackPlugin()], mode: 'development' };Copy the code

6.4 Resolve = Resolve module rules

const { resolve } = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/js/index.js', output: { filename: 'js/[name].js', path: resolve(__dirname, 'build') }, module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'] } ] }, plugins: [new HtmlWebpackPlugin()], mode: 'development', // The main code is here // resolve: {// configure the path alias: // When writing code, we do not need to use import('.. /.. / biggest ss ') / / directly with the import (' $CSS. The biggest ss) can alias: {$CSS: Resolve (__dirname, 'SRC/CSS ')}, // use const b = import('.. /.. // const b = import('.. /.. Js ', '.json', '.jsx', '.css'], // tells Webpack which directory to go to. Modules: [resolve(__dirname, '../../node_modules'), 'node_modules'] } };Copy the code

6.5 devServer => Only in the development environment

const { resolve } = require('path'); Module. exports = {devServer: {// run code directory contentBase: Resolve (__dirname, 'build'), // Monitor all files in contentBase, reload watchContentBase: true, watchOptions: Ignored: /node_modules/}, // Start gzip compress: true, // Port: 5000, // host: 'localhost', // automatically open browser open: true, // enable HMR function hot: true, // Do not display startup server log information clientLogLevel: 'none', / / in addition to start with some basic information, other content don't display the -quiet: true, / / if make a mistake, not full screen prompts to overlay: false, / / server agent - > solve the problem of development environment cross-domain proxy: // Once devServer(5000) receives a request for/API/XXX, it forwards the request to another server (3000) '/ API ': {target: 'http://localhost:3000', // request pathRewrite: / API/XXX --> / XXX (remove/API) pathRewrite: {'^/ API ': '}}}}} 'Copy the code

6.6 Optimization => Only in the production environment is meaningful

const TerserWebpackPlugin = require('terser-webpack-plugin') module.exports = { mode: 'production', optimization: {usedExports: true, // this is used to mark [chunks] splitChunks: {chunks: 'all' // this is the default value. MaxSiza: 0, // Max minChunks: 1, // Chunks to be extracted can be referenced at least once. MaxAsyncRequests: MaxInitialRequests: 3, // maxInitialRequests: 3, // automaticNameDelimiter: '~', // name connecter name: True, // Groups that split chunks // node_modules files are packaged into vendors group chunks using the naming convention cacheGroups: {// Vendors group chunks can be vendors group chunks. --> vendors~xxx.js // Satisfy the common rules above, e.g., be larger than 30KB and be referenced at least once. Vendors: {test: /[\\/]node_modules[\\/]/, // Priority: -10}, default: {// Chunks to be extracted are referenced minChunks at least 2 times: 2, // Priority: -20, // If the current module to be packaged is the same module that has been extracted before, it will be reused instead of reuseExistingChunk: }} */ / This is the default value, you can not write ~}, // the current module record other modules hash file runtime // resolve: modify a file to b file contenthash change runtimeChunk: { name: entrypoint => `runtime-${entrypoint.name}` }, // minimize: True tells Webpack to minimize bundles using TerserPlugin or another plugin defined in Optimization. minimizer: New TerserWebpackPlugin({// Enable the cache cache: Parallel: true, // start sourceMap: true})]}};Copy the code

Links to webpack’s interview questions