Complete knowledge of Vue2's webpack and the use of M (the most complete and complete version of webpack related knowledge)

Vue's WebPack related knowledge

1. The basic use of webpack

1. Concept

webpack is a specific solution for front-end project engineering.

2. Main functions

It provides friendly front-end modular development support, as well as powerful functions such as code compression and obfuscation, processing browser-side JavaScript compatibility, and performance optimization. (that is, programmers can write higher-level code, and webpack will automatically convert high-level code into low-level code)

3. Advantages

Let programmers focus on the realization of specific functions, which improves the efficiency of front-end development and the maintainability of the project.
Note: At present, front-end projects such as Vue and React are basically developed based on webpack.

Two, webpack application

1. Realize interlaced color changing function

1.1 Create a new project blank directory

(1) In the current directory, open the terminal and run the npm init -y command to initialize the package management configuration file package.json

npm init -y

After running successfully, the package.json file will appear in this folder
image.png

1.2 Create a new src source code directory

(1) After creating the src folder, as shown in the figure below
image.png
(2) Click to enter the src folder, and then create two script files, index.html and index.js,
as shown in the figure below
image.png

1.3 Initialize page structure

(1) Open the index.html file with VScode, enter! number, and then press Enter, the following code will appear automatically

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
</html>

(2) Enter under the body tag

ul>li{这是第$个li}*9

(3) Press Enter again, and the relevant code will be automatically generated in the body tag.
The complete structure code is as follows

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul>
        <li>这是第1个li</li>
        <li>这是第2个li</li>
        <li>这是第3个li</li>
        <li>这是第4个li</li>
        <li>这是第5个li</li>
        <li>这是第6个li</li>
        <li>这是第7个li</li>
        <li>这是第8个li</li>
        <li>这是第9个li</li>
    </ul>
</body>
</html>

1.4 Install jQuery

Run the npm install jquery -S command to install jQuery

npm i jquery -S

After the installation is successful, as shown below
image.png

1.5 Import jQuery through ES6 modularization

(1) Import commands in the index.js file

// 1.使用ES6导入语法,导入jQuery
import $ from 'jquery'

Note: It cannot be used directly in the html page, it must be packaged with webpack before it can be used.
(2) Realize the interlaced color changing effect of the list

// 2.定义jQuery的入口函数
$(function () {
    
    
    // 3.实现奇偶行变色
    // 奇数行为红色
    $('li:odd').css('background-color', 'red')
    // 偶数行为粉红色
    $('li:even').css('background-color', 'pink')
})

1.6 Install webpack module

(1) Run the following command on the terminal

npm install [email protected] [email protected] -D

or

npm install [email protected] [email protected] --save-dev

Note: -D is the abbreviation of –save-dev
(2) If the installation error is reported,
the solution

首先删除该项目中下载好的node_modules
再删除该项目中package-lock.json文件
以管理员权限执行下面的命令:
再清除npm缓存 npm cache clean --force
最后npm install
再重新执行npm install [email protected] [email protected] -D
应该就没问题了

1.7 Configure webpack in the project

(1) In the project root directory, create a webpack configuration file named webpack.config.js, and initialize the basic configuration as follows.
At the same time, it represents the running mode of webpack. There are two optional values: development and production.
Use development during development, the packaging time is fast, but the compressed package is large.
Use production during production, the packaging time is slow, but the compressed package is small

// 使用Node.js中的导出语法,向外导出一个webpack的配置对象
module.exports = {
    
    
    mode: 'development'
}

(2) Under the scripts node of package.json, add the dev script as follows

"scripts": {
    
    
    "dev": "webpack"
  }

Note: scripts under the script node can be executed through npm run, such as npm run dev

1.8 Run the command to start webpack to package and build the project

(1) Execute the command

npm run dev

The result is shown as follows and the execution is successful
image.png

1.9 Custom packaging entry and exit

(1) Default conventions in webpack In
webpack 4.x and 5.x versions, there are the following default conventions. The
default packaging entry file is the index.js file in the src directory.
The default output file path is in the dist directory. main.js
Note: You can modify the default contract of packaging in webpack.config.js
(2) You can specify the entrance and exit of packaging
In the webpack.config.js configuration file, specify the entrance of packaging through the entry node, and specify the packaging through the output node exit.

const path = require('path')

module.exports = {
    
    
    // 代表webpack运行的模式,可选值有两个development 和 production
    mode: 'development',
    // 自定义打包入口文件的路径
    entry: path.join(__dirname,'./src/index1.js'),
    // 自定义生成的文件的存放路径
    output: {
    
    
        // 存放到目录 
        path: path.join(__dirname, 'dist'),
        // 生成的文件名
        filename: 'mian1.js'
    }
}

1.10 Import the packaged js file in the code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../dist/main1.js"></script>
</head>
<body>
    <ul>
        <li>这是第1个li</li>
        <li>这是第2个li</li>
        <li>这是第3个li</li>
        <li>这是第4个li</li>
        <li>这是第5个li</li>
        <li>这是第6个li</li>
        <li>这是第7个li</li>
        <li>这是第8个li</li>
        <li>这是第9个li</li>
    </ul>
</body>
</html>

The result is as follows
image.png

2. Plugins in webpack

2.1 The role of webpack plugin

By installing and configuring third-party plug-ins, the capabilities of webpack can be expanded, making webpack more convenient to use.

2.2 webpack-dev-server plugin

(1) Introduction
Whenever the source code is modified, webpack will automatically package and build the project.
(2) command

npm install [email protected] -D

Note: Turn off VSCode or other software that opens this folder during installation.
(3) Configure webpack-dev-server
to modify the dev command under scripts in package.json

"scripts": {
    
    
    "dev": "webpack serve"
  },

(4) Repackage the project

npm run dev

(5) Visit the http://localhost:8080 address in the browser to check the automatic packaging effect.
(6) If an error is reported, the solution is as follows
Reinstall the webpack-cli dependent module

npm install webpack-cli --save-dev

rerun

npm run dev

Note: webpack-dev-server will start a real-time packaged http server, and will put the packaged files in the memory, so if you open the page locally, the relevant things will not change, only through http://localhost: 8080/src to see real-time changes, and the imported code must be modified to
image.png

2.3 html-webpack-plugin

(1) Introduce
the HTML plugin in webpack (similar to a template engine plugin)
(2) Command

npm install [email protected] -D

(3) Related use

// 1.导入HTML插件,得到一个构造函数
const HtmlPlugin = require('html-webpack-plugin')

// 2.创建HTML插件的实例对象
const htmlPlugin = new HtmlPlugin({
    
    
    template: './src/index.html', // 指定原文件的存放路径
    filename: './index.html', //指定生成的文件的存放路径
})

// 使用Node.js中的导出语法,向外导出一个webpack的配置对象
module.exports = {
    
    
    // 代表webpack运行的模式,可选值有两个development 和 production
    mode: 'development',
    // 3.通过plugins节点,使htmlPlugin插件生效
    // 插件的数组,将来webpack在运行时,会加载并调用这些插件
    plugins: [htmlPlugin],
}

(4) Run command

npm run dev

When accessing through http://localhost:8080, the page will appear directly.
(5) Note
When using the html-webpack-plugin plug-in, the index.html page copied to the root directory of the project through the HTML plug-in is also placed in memory.
The HTML plugin automatically injects the packaged index.js file into the generated index.html page.
So there is no need to import it in the code, it will be rendered automatically.

2.4 devServer node

(1) Introduction
In the webpack.config.js configuration file, you can configure more webpack-dev-server plug-ins through the devServer node
(2) Related codes

devServer: {
    
    
        // 首次打包成功后,自动打开浏览器
        open: true,
        // 在http协议中,如果端口号是80,则可以被省略
        port: 92,
        // 指定运行的主机地址
        host: '127.0.0.1'
}

(3) The location in the webpack.config.js configuration file

module.exports = {
    
    
    mode: 'development',
    devServer: {
    
    
        // 首次打包成功后,自动打开浏览器
        open: true,
        // 在http协议中,如果端口号是80,则可以被省略
        port: 92,
        // 指定运行的主机地址
        host: '127.0.0.1'
    }
}

result
image.png

3. The loader in webpack (loader)

3.1 loader overview

In the actual development process, webpack can only package and process modules ending with the .js suffix by default. Other modules that do not end with the .js suffix cannot be processed by webpack by default, and the loader needs to be called to package normally, otherwise an error will be reported.

3.2 Function

The role of the loader loader is to assist webpack in packaging and processing specific file modules
css-loader can package and process css-related files
less-loader can package and process less-related files
babel-loader can package and process advanced JS syntax that webpack cannot handle

3.3 Packaging and processing css files

(1) Install the loader command for processing css files

npm i [email protected] [email protected] -D

(2) In the rules array in the module of webpack.config.js, add loader rules.

module: {
    
    
   rules: [
            // 定义了不同模块对应的loader
            // 文件名后缀名的匹配规则
            {
    
    test: /\.css$/, use:['style-loader','css-loader']}
   ]
}

Among them, test indicates the matching file type, and use indicates the position of the corresponding loader
(3) in the webpack.config.js configuration file to be called

module.exports = {
    
    
    mode: 'development',
    module: {
    
    
        rules: [
            // 定义了不同模块对应的loader
            // 文件名后缀名的匹配规则
            {
    
    test: /\.css$/, use:['style-loader','css-loader']}
        ]
    }
}

(4) Code in index.js

import './css/index.css'

(5) The code corresponding to the css file

html,
body,
ul {
    
    
  margin: 0;
  padding: 0;
}
html li,
body li,
ul li {
    
    
  line-height: 30px;
  padding-left: 20px;
  font-size: 12px;
}

result
image.png

3.4 Process of processing css

(1) When webpack finds that a file cannot be processed, it will search for the configuration file webpack.config.js to see if the corresponding loader is configured in the module.rules array.
(2) webpack transfers the Index.css file to css-loader for processing
(3) when css-loader finishes processing, it transfers the processing result to style-loader
(4) when style-loader finishes processing After that, there is no next loader, so the processing result is transferred to webpack
(5) webpack merges the result of style-loader processing into /dist/index.js, and finally generates a packaged file.

3.5 Packaging and processing less files

(1) Install commands to process less files

npm i [email protected] [email protected] -D

(2) In the rules array in the module of webpack.config.js, add loader rules.

 module: {
    
    
        rules: [
            // 定义了不同模块对应的loader
            // 处理 .less文件的loader
            {
    
    test:/\.less$/, use:['style-loader','css-loader','less-loader']}
        ]
}

(3) The location in the webpack.config.js configuration file

module.exports = {
    
    
    mode: 'development',
    module: {
    
    
        rules: [
            // 定义了不同模块对应的loader
            // 处理 .less文件的loader
            {
    
    test:/\.less$/, use:['style-loader','css-loader','less-loader']}
        ]
    }
}

(4) Code in index.js

import './css/index.less'

(5) The code corresponding to the less file

html,
body,
ul {
    
    
    margin: 0;
    padding: 0;
    li{
    
    
        line-height: 30px;
        padding-left: 20px;
        font-size: 12px;
    }
}

result
image.png

3.6 Pack and process files related to url path

(1) Install commands that process files related to url paths

npm i [email protected] [email protected] -D

(2) In the rules array in the module of webpack.config.js, add loader rules.

module: {
    
    
        rules: [
            // 定义了不同模块对应的loader
            // 处理 图片的loader
            // 如果 需要调用的loader只有一个,则只传递一个字符串也行,如果有多个loader,则必须指定数组
            {
    
    test: /\.jpg|png|gif$/, use: 'url-loader?limit=22229'},
        ]
}

Note:
limit is used to specify the size of the image, and the unit is byte (byte).
Only images smaller than or equal to the limit size will be converted to base64 format images.
It is recommended to convert small images into base64 for quick loading without sending multiple requests.
(3) The location in the webpack.config.js configuration file

module.exports = {
    
    
    mode: 'development',
    module: {
    
    
        rules: [
            // 定义了不同模块对应的loader
            // 处理 图片的loader
            // 如果 需要调用的loader只有一个,则只传递一个字符串也行,如果有多个loader,则必须指定数组
            {
    
    test: /\.jpg|png|gif$/, use: 'url-loader?limit=22229'},
        ]
    }
}

(4) Code in index.js

// 导入图片,得到图片文件
import logo from './images/logo.jpg'
// 给img标签的src动态赋值
$('.box').attr('src',logo)

(5) Corresponding code

<img src="" alt="" class="box">

result
image.png

3.7 The process of webpack processing styles

Import style (in webpack, everything is a module, which can be imported and used through ES6 import syntax).
If in a module, the member received by using from is undefined, it does not need to receive

3.8 Packaging and processing advanced syntax in js

(1) Introduction
webpack can only package and process some advanced JavaScript syntax. For some advanced js syntax that webpack cannot handle, you need to use babel-loader to package and process.
(2) command

npm i [email protected] @babel/[email protected] @babel/[email protected] -D

(3) In the rules array in the module of webpack.config.js, add loader rules.

module: {
    
    
        rules: [
            // 使用babel-loader处理高级js语法
            // 在配置babel-loader的时候,只需要把自己的代码进行转换即可,要排除node_modules目录中的JS文件
            // 因为第三方包中的JS兼容性,不需要关心
            {
    
    
                test: /\.js$/,
                use: 'babel-loader', exclude: /node_modules/
            },
        ]
    }

(4) The location in the webpack.config.js configuration file

module.exports = {
    
    
    mode: 'development',
    module: {
    
    
        rules: [
            // 使用babel-loader处理高级js语法
            // 在配置babel-loader的时候,只需要把自己的代码进行转换即可,要排除node_modules目录中的JS文件
            // 因为第三方包中的JS兼容性,不需要关心
            {
    
    
                test: /\.js$/,
                use: 'babel-loader', exclude: /node_modules/
            },
        ]
    }
}

(5) In the project root directory, create a configuration file named babel.config,js

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

(6) Write the test code in the index.js file

// 定义装饰器函数
function info(target) {
    
    
    target.info = 'Person info'
}

// 定义一个普通的类
@info
class Person{
    
    }

console.log(Person.info)

result
image.png

4. Package release of webpack

4.1 Configure build command

(1) Under the scripts node in the package.json file, the build command is as follows

"scripts": {
    
    
    "dev": "webpack serve",
    "build": "webpack --mode production"
  },

--mode is a parameter item used to specify the operating mode of webpack. production represents the production environment, and code compression and performance optimization will be performed on the packaged and generated files.
Note: The parameter item specified by –mode will override the mode option in webpack.config.js. --mode takes precedence over the mode option.

4.2 Optimize the storage location of pictures and js files

(1) Modify the js file generation path in the webpack.config.js file

const path = require('path')

module.exports = {
    
    
    // 代表webpack运行的模式,可选值有两个development 和 production
    mode: 'development',
    // entry: '指定要处理哪个文件'
    entry: path.join(__dirname, './src/index.js'),
    // 指定生成的文件要存放到哪里
    output: {
    
    
        // 存放的目录
        path: path.join(__dirname, 'dist'),
        // 生成的文件路径
        filename: 'js/index.js'
    },
}

The result after successful generation
image.png
(2) Modify the url-loader configuration item in webpack.config.js, and add the outputPath option to specify the output path of the image file.
Clearly specify to store the image files generated by packaging in the image folder under the dist directory

module.exports = {
    
    
    // 代表webpack运行的模式,可选值有两个development 和 production
    mode: 'development',
    module: {
    
    
        rules: [
            // 处理 图片的loader
            {
    
    
                test: /\.jpg|png|gif$/,
                // 配置url-loader的时候,多个参数之间,使用&符号进行分隔
                use: 'url-loader?limit=470&outputPath=images',
            },
        ]
    }
}

result
image.png

4.3 Configure and use the clean-webpack-plugin plugin

(1) Installation command

npm install --save-dev clean-webpack-plugin

(2) Add code in webpack.config.js

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

module.exports = {
    
    
    // 代表webpack运行的模式,可选值有两个development 和 production
    mode: 'development',
    // 通过plugins节点,使htmlPlugin插件生效
    // 插件的数组,将来webpack在运行时,会加载并调用这些插件
    plugins: [htmlPlugin, new CleanWebpackPlugin()],
}

5、Source Map

5.1 Introduction

Source Map is an information file, which stores location information. That is to say, the source map file stores the compressed and obfuscated code, corresponding to the position before conversion. If something goes wrong, the debugging tool will directly display the original code instead of the converted code, which can greatly facilitate later debugging.

5.2 In the development environment, accurately locate the specific error line (suggestion)

Add the following code in webpack.config.js

module.exports = {
    
    
    // 代表webpack运行的模式,可选值有两个development 和 production
    mode: 'development',
    // 此选项生成的Source Map能够保证“运行时报错的行数” 与 “源代码的行数”保持一致
    devtool: 'eval-source-map',
}

5.3 In the production environment, when an error occurs, the number of lines is located and the source code is also exposed (not recommended)

Add the following code in webpack.config.js

module.exports = {
    
    
    // 代表webpack运行的模式,可选值有两个development 和 production
    mode: 'development',
    // 此选项生成的Source Map能够保证“运行时报错的行数” 与 “源代码的行数”保持一致
    devtool: 'source-map',
}

5.4 In the production environment, when an error occurs, only the line number is located, and the source code is not exposed (recommended)

Add the following code in webpack.config.js

module.exports = {
    
    
    // 代表webpack运行的模式,可选值有两个development 和 production
    mode: 'development',
    // 此选项生成的Source Map能够保证“运行时报错的行数” 与 “源代码的行数”保持一致
    devtool: 'nosources-source-map',
}

It is convenient for users to debug and improve website security

5.5 Attention

When publishing the project, it is recommended to turn off the devtool option, then the final generated file does not contain Source Map. This prevents the original code from being exposed to others in the form of Source Map.

6. Expansion

6.1 Replace the src directory with @

(1) The code is as follows

module.exports = {
    
    
    // 代表webpack运行的模式,可选值有两个development 和 production
    mode: 'development',
    resolve: {
    
    
        alias: {
    
    
            // 用@符号表示src这一层目录
            '@': path.join(__dirname, './src/')
        }
    }
}

(2) Related application
examples are as follows:

import '@/css/index.css'

Guess you like

Origin blog.csdn.net/qq_46106857/article/details/128937400