webpack basics

Basic use of webpack
webpack installation

Run npm i webpack webpack-cli -D in the terminal of the project

Configure webpack in the project

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

module.exports={
    
    
    // 代表webpack运行的模式,可选值有两个 development 和 production
    mode:'development'
}

Under the script node of package.json, add the dev script as follows:

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

There are two optional values ​​for the mode node, which are:

The development environment
will not perform code compression and performance optimization on the files generated by the package.
The packaging speed is fast and is suitable for use in the development stage
. ② The
production environment
will perform compression on the files generated by the package. Code compression and performance optimization.
The packaging speed is very slow and is only suitable for use in the project release phase .

Default conventions in webpack
  • The default packaging entry file src ->index.js
  • The default output file path dist->main.js

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

Custom packaged entry and exit

In the webpack.config.js configuration file, specify the packaging entry through the entry node. Specify the packaged export through the output node.

const path = require('path')//导入node.js中专门操作路径的模块
//使用node.js中的导出语法,向外导出一个webpack的配置对象
module.exports={
    
    
    // 代表webpack运行的模式,可选值有两个 development 和 production
    mode:'development',
    entry:path.join(__dirname,'./src/index.js'),//打包入口文件的路径
    output:{
    
    
        path:path.join(__dirname,'./dist'),//输出文件的存放路径
        filename:'bundle.js'//输出文件的名称
    }
}
webpack plugin

. The two most commonly used webpack plug-ins are as follows:
① webpack-dev-server
is similar to the nodemon tool used in the node.js stage.
Whenever the source code is modified, webpack will automatically package and build the project
② html-webpack-plugin
webpack The HTML plug-in in (similar to a template engine)
can be used to customize the content of the index.html page.
webpack-dev-server allows webpack to monitor changes in the project source code to automatically package and build.

Install webpack-dev-server

Run the following command to install this plug-in in the project:
npm i webpack-dev-server -D

Configure webpack-dev-server

① Modify the dev command in package.json -> scripts as follows:

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

② Run the npm run dev command again to repackage the project. ③ Access the http://localhost:8080
address in the browser to check the automatic packaging effect. The bundle.js generated is virtual and output in the root directory of the project. webpack output is served from / can be displayed through http://localhost:8080/bundle.js You need to modify the reference to bundle.js in the project

Please add image description

// 加载和引用内存中的bundle.js 
<script src="/bundle.js"></script>
Install html-webpack-plugin

Run the following command to install this plug-in in the project:
npm i html-webpack-plugin -D

The http://localhost:8080 address we have packaged does not have an index.html page. It is a root directory
. html-webpack-plugin is an HTML plug-in in webpack. You can customize the content of the index.html page through this plug-in.
Requirement: Copy the index.html homepage in the src directory to the project root directory through the html-webpack-plugin plug-in!

Configure html-webpack-plugin
//导入html插件,得到一个构造函数
const HtmlPlugin = require('html-webpack-plugin')
//创建HTML插件的实例对象
const htmlPlugin = new HtmlPlugin({
    
    
    template:'./src/index.html', //指定源文件的存放地址
    filename:'./index.html', //指定生成文件的存放路径
})
module.exports={
    
    
    // 代表webpack运行的模式,可选值有两个 development 和 production
    mode:'development',
    plugins:[htmlPlugin], //通过plugins节点,使htmlPlugin插件生效
    
}
Solve the confusion html-webpack-plugin

① The index.html page copied to the project root directory through the HTML plug-in is also placed in the memory
② The HTML plug-in automatically injects the packaged bundle.js file at the bottom of the generated index.html page
Purpose: We access http: // The root directory of localhost:8080 has index.html, which can be displayed directly.

devServernode

In the webpack.config.js configuration file, you can configure more webpack-dev-server plug-ins through the devServer node. The sample code is as follows:

devServer:{
    
    
        open:true,//初次打包完成后,自动打开浏览器
        host:'127.0.0.1', //初次打包所使用的主机地址
        port:80,//实时打包所使用的端口号
    }

Note: If you modify the webpack.config.js configuration file or modify the package.json configuration file, you must restart the real-time packaging server, otherwise the latest configuration file will not take effect!

loader in webpack

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 a .js suffix cannot be processed by webpack by default. You need to call the loader to package normally , otherwise an error will be reported!
The role of loader is to assist webpack in packaging and processing specific file modules . For example:
⚫ 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

Package and process css files

① Run the npm i style-loader css-loader -D command to install the loader that processes CSS files.
② In the module -> rules array of webpack.config.js, add the loader rules as follows:

rules:[//文件后缀名的匹配规则
        {
    
    test:/\.css$/,use:['style-loader','css-loader']}
    ]

Among them, test represents the matching file type, use represents the corresponding loader to be called.
Note:
⚫ The order of loaders specified in the use array is fixed
⚫ The calling order of multiple loaders is: calling from back to front

Package and process less files

① Run npm i less-loader less -D command
② In the module -> rules array of webpack.config.js, add the loader rules as follows:

rules:[//文件后缀名的匹配规则
	//loader调用顺序是从后往前
    {
    
    test:/\.less$/,use:['style-loader','css-loader','less-loader']},
]
Packaging and processing of files related to url paths in style sheets

① Run the npm i url-loader file-loader -D command
② In the module -> rules array of webpack.config.js, add the loader rules as follows:
The first way of writing

rules:[//文件后缀名的匹配规则
	{
    
    test:/\.jpg|png|gif$/,use:'url-loader?limit=22229'},
]

The second way of writing

rules:[//文件后缀名的匹配规则
	{
    
    
        test:/\.jpg|png|gif$/, //匹配图片文件
        use:{
    
    
             loader:'url-loader',//通过loader属性指定要调用的loader
             options:{
    
     //同options属性指定参数项
                    limit:22229
                }
            }
    }
]

Among them, what follows ? are the parameters of the loader: ⚫ limit is used to specify the size of the picture, the unit is byte (byte) ⚫ Only pictures ≤ limit size will be converted to base64 format pictures

Advanced syntax for packaging and processing js files

webpack can only package and process a part of advanced JavaScript syntax. For those advanced js syntax that webpack cannot handle, you need to use babel-loader for packaging processing.

Install babel-loader related packages

Run the following command to install the corresponding dependency package:
npm i babel-loader @babel/core @babel/plugin-proposal-class-properties -D

Configure babel-loader

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

{
    
    
      test:/\.js$/,
      //exclude为排除项
      // 表示babel-loader只需要处理开发者编写的js文件,不需要处理node_modules下的js文件
      exclude:/node_modules/,
	  use:{
    
    
      	loader:'babel-loader',
     	 options:{
    
     //参数项
      	//声明一个babel插件,此插件用来转化class中的高级语法
            plugins:['@babel/plugin-proposal-class-properties'],
      	}
     }
}
Package and publish
Configure webpack packaging and publishing

Under the scripts node of the package.json file, add the build command as follows:

"scripts": {
    
    
    "dev": "webpack serve",  //开发环境中,运行dev命令
    "build":"webpack --mode production"  //项目发布时,运行build命令
  },

–model is a parameter used to specify the running mode of webpack. Production represents the production environment, and will perform code compression and performance optimization on the files generated by packaging.
Note: The parameters specified through --model will override the model option in webpack.config.js.

Generate JavaScript files into the js directory
output:{
    
    
   path:path.join(__dirname,'./dist'),//输出文件的存放路径
   //明确告诉webpack把生成的bundle.js文件存放到dist目录下的js目录中
   filename:'js/bundle.js'
},
Generate image files into the image directory
{
    
    
            test:/\.jpg|png|gif$/,
            use:{
    
    
                loader:'url-loader',//通过loader属性指定要调用的loader
                options:{
    
     //同options属性指定参数项
                    limit:22228,
                    outputPath:'image',
                }
            }
        },
Automatically clean up old files in the dist directory

In order to automatically clean up old files in the dist directory every time you package and publish , you can install and configure the clean-webpack-plugin plug-in:
Now run the following command in the project terminal
npm i clean-webpack-plugin -D

Configure clean-webpack-plugi
//按需导入插件,得到插件的构造函数之后,创建插件的实例对象
const {
    
    CleanWebpackPlugin} = require('clean-webpack-plugin')
const cleanPlugin = new CleanWebpackPlugin()
plugins:[htmlPlugin,cleanPlugin], //通过plugins节点,挂载插件
Source Map
Source Map in webpack development environment

In the development environment, webpack enables the Source Map function by default. When an error occurs while the program is running, you can directly prompt the location of the error line on the console and locate the specific source code.

Problem with default Source Map

The Source Map generated by default in the development environment records the location of the generated code. This will cause the problem that the number of lines in the runtime error is inconsistent with the number of lines in the source code.

Solve the problem of default Source Map


In a development environment, it is recommended to add the following configuration to webpack.config.js to ensure that the number of error lines at runtime is consistent with the number of lines of source code :
eval-source-map is only used in development mode and is not recommended. Use in production mode

module.exports={
    
    
    mode:'development',
    devtool:'eval-source-map',
}
Source Map in webpack production environment

In a production environment , if the devtool option is omitted , the Source Map will not be included in the final generated file . This prevents the original code from being exposed to unauthorized parties through the Source Map.
In a production environment, if you only want to locate the specific number of lines where the error was reported , and do not want to expose the source code . At this time, the value of devtool can be set to nosources-source-map .
In a production environment, if you want to display the source code of the specific error while locating the number of error lines . At this time, the value of devtool can be set to source-map. After using this option: You should configure your server to not allow ordinary users to access the source map file!

Best Practices for Source Maps

① In development environment:
⚫ It is recommended to set the value of devtool to eval-source-map
⚫ Benefit: You can pinpoint the specific error line
② In production environment:
⚫ It is recommended to turn off Source Map or set the value of devtool to nosources-source- map
⚫ Benefits: Prevent source code leakage and improve website security

Guess you like

Origin blog.csdn.net/qq_48439911/article/details/125874098