Concept:

Webpack is a concrete solution for front-end project engineering.

Of course, vue-CLI can be generated directly

Main functions:

It provides friendly front-end modular development support, as well as powerful features such as code compression and obfuscation, handling browser-side JavaScript compatibility, and performance optimization.

Benefits:

Let programmers focus on the implementation of specific functions, improve front-end development efficiency and project maintainability.

use

1, install,

Run the following command from the terminal to install the two packages associated with WebPack:

NPM install [email protected] [email protected] -dCopy the code

-s stands for –save-d stands for –save-dev

2, configuration,

🍎2.1. In the project root directory, create a webpack configuration file named webpack.config.js and initialize the following basic configuration:

Module. exports = {mode: 'development' //mode specifies the build mode. Optional values are development and production}Copy the code

Explanation:

Mode optional values

The development environment does not perform code compression and performance optimization on the files generated by packaging. The packaging speed is fast and suitable for use in the development stage

The Production environment compresses the code and optimizes the performance of the files generated by packaging. Packaging is slow and is only suitable for use during the project release phase

🍎2.2. In the scripts node of package.json, add the following dev script:

"Scripts" : {"dev" : "webpack" // script is a script under the node, which can be executed using NPM run. Example: NPM run dev}Copy the code

Webpack.config. js is a configuration file for Webpack. Webpack reads this configuration file to package the project based on the given configuration before actually starting to package the build. Note: Since WebPack is a packaging tool developed based on Node.js, its configuration file supports webPack customization using Node.js-related syntax and modules.

🍎2.3. Run the NPM run dev command in the terminal to start webpack to build the project

Importing the case into the packaged generated main.js will work

Default conventions in Webpack Versions 4.x and 5.x have the following default conventions: The default package entry file is SRC -> index.js and the default output file is dist -> main.js

Note: You can change the default convention for packaging in webpack.config.js

⭐⭐⭐ Customizes the entrance and exit of packaging

In the webpack.config.js configuration file, specify the entry to the package through the Entry node. Specify the packaged exit through the output node. Example code is as follows:

Module. exports = {//mode: 'development', //mode specifies the build mode. Optional values include development and production entry: path.join(__dirname, './ SRC /index.js'),// Package entry file path output: {path: Path. join(__dirname, 'dist'),// output file path filename: 'bundle.js'// output filename}}Copy the code

In the webpack plug-in

What plug-ins do

By installing and configuring third-party plug-ins, you can extend the power of WebPack and make it easier to use. The most commonly used

Webpack-dev-server automatically packages builds

Similar to the Nodemon tools used in the Node.js phase, webPack will automatically package and build the project whenever the source code is modified

use

1, install,

NPM install [email protected] - DCopy the code

There are pit webpack-cli internal i.e. project version must be around 4.9.0

2, configuration,

2.1, modify package.json -> scripts dev:
"Scripts ": {"dev" : "webpack serve" // scripts under the node, can be executed by NPM run},Copy the code
2.2. Run the NPM run dev command again to package the project again
2.3. Access in a browserhttp://localhost:8080Address to view the effect of automatic packaging

Note: Webpack-dev-server starts a live packaged HTTP server

Where are the files generated by packaging?

1. If webpack-dev-server is not configured, the generated files generated by webpack are stored on physical disks

Strictly follow the configuration specified by the developer in webpack.config.js

Store according to the path specified by the output node

2. After webpack-dev-server is configured, the generated files are stored in the memory

The path specified by the output node is not saved to the actual physical disk

Improved performance for real-time packaged output because memory is much faster than physical disk

How can I access files generated in memory?

The files generated by webpack-dev-server into memory are placed in the root directory of the project by default and are virtual and invisible

You can directly use/to represent the project root directory, followed by the name of the file to access, you can access the file in memory

For example, /bundle.js means to access the bundle.js file generated by webpack-dev-server into memory

/bundle.js ⭐⭐⭐ references js

html-webpack-plugin

Html-webpack-plugin is an HTML plug-in in Webpack that allows you to customize the contents of an index. HTML page.

Need: use the html-webpack-plugin to copy the index.html home page from the SRC directory to the root directory of the project. Access to the home page

use

1, install,

NPM install [email protected] - DCopy the code

2, configuration,

/ / 1. Const HtmlPlugin = require('html-webpack-plugin') // 2 Const htmlPlugin = new htmlPlugin ({template: // SRC /index.html',// specify the path of the original file filename:'./index.html' // specify the path of the generated file}) module.exports = {mode: 'development', plugins: [htmlPlugin],// 3. ⭐ enable htmlPlugin to take effect via plugins}Copy the code

The index.html page, copied to the project root directory via the HTML plug-in, is also put into memory

The HTML plugin automatically injects the bundled bundle.js file into the generated index.html page

DevServer node

In the webpack.config.js configuration file, you can configure more of the webpack-dev-server plug-in through the devServer node,

Example code is as follows:

DevServer: {open: true,// host: '127.0.0.1',// host address used for real-time packaging port: 80,// Port number used for real-time packaging}Copy the code

The loader in webpack

Summary of the loader

In actual development, WebPack can only package modules with.js extensions by default. Other modules that do not end with.js suffix cannot be processed by webpack by default. You need to call loader to pack normally, otherwise an error will be reported.

Loader helps WebPack process specific file modules. Such as:

Css-loader can package csS-related files

Less-loader can package files related to. Less-loader

Babel-loader can be packaged to handle advanced JS syntax that WebPack cannot handle

Package and process CSS files

1. Run the NPM I [email protected] [email protected] -d command to install the Loader that processes CSS files

2. Add loader rules to webpack.config.js module===> rules array as follows:

Module: {// Matching rules for all third-party file modules rules: [// matching rules for file name extensions {test: /\.css$/, use: ['style-loader', 'css-loader']}]}Copy the code

Test indicates the matched file type, and use indicates the loader to be invoked

Note:

The loader order specified in the use array is fixed

Multiple Loaders are invoked in the following order: from back to front

Package and process less files

1. Run the NPM I [email protected] [email protected] -d command

Add loader rules to webpack.config.js module-> rules array as follows:

Module: {// Matching rules for all third-party file modules rules: [// Matching rules for file name extensions {test: /\.less$/,use:['style-loader','css-loader','less-loader'] }, ] }Copy the code

Package files related to the URL path in the processing stylesheet

1. Run the NPM I [email protected] [email protected] -d command

Add loader rules to webpack.config.js module-> rules array as follows:

Module: {// All third party file modules matching rules rules: [// file suffix matching rules // If only one loader is required, it means passing a string. If there are multiple loaders, you must specify array {test: /\.jpg|png|gif$/,use: 'url-loader?limit=22229'} ] }Copy the code

Among them? The loader argument follows:

Limit specifies the size of the image in bytes.

Only images of a size ≤ limit will be converted to Base64

Package handles advanced syntax in JS files

Webpack can only be packaged to handle a portion of advanced JavaScript syntax. For advanced JS syntax that WebPack can’t handle, borrow

Help with babel-loader for packaging. For example, Webpack cannot handle the following JavaScript code:

/ / 1. Function info(target) {// 2 Add static attribute info target.info = 'Person info'} //3 to the target. Apply the info decorator @info class Person {} // 4 to the Person class. Print the static property of Person info console.log(person.info)Copy the code

Install babel-loader related packages

Run the following command to install the dependency packages:

NPM I [email protected] @babel/[email protected] @babel/[email protected] -dCopy the code

In the module-> rules array of webpack.config.js, add the loader rule as follows:

// Note that exclude must be specified with exclude; Js $/, use: 'babel-loader',exclude: /node_modules/}Copy the code

Configure the Babel – loader

In the project root directory, create a configuration file named babel.config.js and define the following configuration items for Babel

Module.exports = {plugins: [['@babel/plugin-proposal-decorators', {legacy: true}]]}Copy the code

Packaging releases

Why package it

After the completion of project development, webpack is needed to package and publish the project, mainly for the following two reasons:

In the development environment, the generated files are stored in the memory and cannot be obtained

In the development environment, the generated files are not compressed or optimized for performance

In order for the project to run in a production environment with high performance, the project needs to be packaged and released.

Configure the packaged publishing of WebPack

In the package.json file, add the following build command under the scripts node

"Scripts ": {"dev" : "webpack serve",// in development environment, run dev command "build": "webpack --mode production" // when the project is published, run build command},Copy the code

–mode is a parameter that specifies the running mode of webPack. Production represents the production environment, which is used to package generated files

Code compression and performance optimization.

Note: The model option in webpack.config.js is overridden by the parameter specified by –model.

Generate JavaScript files into a js directory

In the output node of the webpack.config.js configuration file, do the following:

Output: {path: path.join(__dirname, 'dist '), // Explicitly tell webpack to store the generated bundle.js file in the js subdirectory of dist in filename: 'js/bundle. Js'}Copy the code

Generate the image file into the image directory

Modify the url-loader configuration item in webpack.config.js and add the outputPath option to specify the outputPath of the image file:

/ / specify the image files generated from packaging, store the image folder under the dist directory {test: / \. JPG | PNG | GIF $/, use: 'url - loader? Limit = 22229 & outputPath = images'},Copy the code

Automatically clean up old files in the dist directory

To automatically clean up old files in the Dist directory every time a package is published, you can install and configure the clean-Webpack-plugin: NPM search

/ / 1. NPM install --save-dev clean-webpack-plugin -d // 2 Const {CleanWebpackPlugin} = require('clean-webpack-plugin'); const {CleanWebpackPlugin} = require('clean-webpack-plugin'); Const cleanPlugin=new CleanWebpackPlugin() // 3. Plugins: [htmlPlugin,cleanPlugin],// Mount the pluginCopy the code

Source Map

1. Problems encountered in production environment

Before the front-end project is put into production environment, it is necessary to compress and confuse the JavaScript source code, so as to reduce the file size and improve the file size

Loading efficiency. This inevitably raises another question:

Debugging code after compression obfuscation is extremely difficult

Variables are replaced with names without any semantics

Blank lines and comments are removed

  1. A Source Map is an information file that stores location information. In other words, the Source Map file stores the position of the compressed and obfuscated code before the transformation.

With it, when an error occurs, the debugging tool will directly display the original code, rather than the converted code, which can greatly facilitate later debugging.

  1. Source Map in WebPack Development Environment The Source Map function is enabled in WebPack by default. When a program fails to run, you can prompt the error line directly on the console

Location and locate to specific source code:

3.1 Problems with default Source Map

The Source Map generated by default in the development environment records the location of the generated code. Can cause runtime error lines to be inconsistent with the number of lines in the source code

3.2 Solving the default Source Map problem In the development environment, it is recommended to add the following configuration in webpack.config.js to ensure that the number of error lines is consistent with the number of lines in the Source code:

Module. exports = {mode: 'development', // eval-source-map is only used in 'development' mode, not recommended in 'production' mode. Devtool: 'eval-source-map', // omits other configuration items... }Copy the code
  1. Source Map in webPack production In production, if the devtool option is omitted, the resulting file does not contain the Source Map. This prevents the original code from passing through

Expose it to someone else in the form of a Source Map.

4.1 Locating only the number of lines without exposing the source code In a production environment, if you only want to locate the specific number of lines with an error and do not want to expose the source code. In this case, you can set devtool to nosource-source-map.

4.2 Locate the number of lines and Expose the source code in the production environment, if you want to locate the number of lines and display the source code of the specific error. You can set the devtool value to source-map.

  1. Best practices for Source Map

In the development environment:

It is recommended to set devtool to eval-source-map

Benefits: Can accurately locate the specific error line

Production environment:

You are advised to disable Source Map or set devtool to nosource-source-map

Benefits: prevent source code leakage, improve site security