Learning record-Webpack configuration

1. webpackOverview

webpackIt is a popular front-end project construction tool (packaging tool) that can solve webthe dilemma faced in current development. webpackProvides friendly modular support , as well as powerful functions such as code compression and confusion , handling jscompatibility issues , performance optimization, etc., so that programmers can focus on the implementation of specific functions, improving development efficiency and project maintainability .

2. webpackBasic use

2.1 Create a list of interlaced color change cases

  1. Create a new project blank directory and run the npm init –ycommand to initialize the package management configuration filepackage.json
  2. New srcsource code directory
  3. New src -> index.htmlhomepage
  4. Initialize the basic structure of the home page
  5. Run the npm install jquery –Scommand, installjQuery
  6. Through the modular form, realize the interlaced color effect of the list

2.2 Installation and configuration in the projectwebpack

  1. Run the npm install webpack webpack-cli –Dcommand to install webpackrelated packages
  2. In the project root directory, create webpack.config.jsa webpackconfiguration file named
  3. In webpackthe configuration file, initialize the following basic configuration:
module.exports = {
    
    
    mode: 'development' // mode 用来指定构建模式
}
  1. Under package.jsonthe scriptsnode in the configuration file , the new devscript is as follows:
"scripts": {
    
    
    "dev": "webpack" // script 节点下的脚本,可以通过 npm run 执行
}
  1. Run the npm run devcommand in the terminal to start the webpackproject packaging

2.3 Configure the entry and exit of the package

webpackThe default convention in the 4.x version:

  • The packaged entry file issrc -> index.js
  • The packaged output file isdist -> main.js

If you want to modify the entry and exit of the package, you can webpack.config.jsadd the following configuration information in it:

const path = require('path'); // 导入 node.js 中专门操作路径的模块
module.exports = {
    
    
    entry: path.join(__dirname, './src/index.js'), // 打包入口文件的路径
    output: {
    
    
        path: path.join(__dirname, './dist'), // 输出文件的存放路径
        filename: 'bundle.js' // 输出文件的名称
    }
}

2.4 Configured webpackautomatic packaging function

  1. Run npm install webpack-dev-server –Dcommands to install tools that support automatic project packaging
  2. Modify package.json -> scriptsthe devcommand as follows:
"scripts": {
    
    
    "dev": "webpack-dev-server" // script 节点下的脚本,可以通过 npm run 执行
}
  1. Will src -> index.html, the scriptscript reference path, modify the"/buldle.js“
  2. Run the npm run devcommand and re-package
  3. Visit the http://localhost:8080address in the browser to check the automatic packaging effect

Note :

  • webpack-dev-serverWill start a real-time packaged httpserver
  • webpack-dev-serverThe output file generated by the package is placed in the project root directory by default, and it is virtual and invisible

2.5 Configure to html-webpack-plugingenerate a preview page

  1. Run the npm install html-webpack-plugin –Dcommand to install the plugin that generates the preview page
  2. Modify the webpack.config.jsfile header area and add the following configuration information:
// 导入生成预览页面的插件,得到一个构造函数
const HtmlWebpackPlugin = require('html-webpack-plugin')
const htmlPlugin = new HtmlWebpackPlugin({
    
     // 创建插件的实例对象
    template: './src/index.html', // 指定要用到的模板文件
    filename: 'index.html' // 指定生成的文件的名称,该文件存在于内存中,在目录中不显示
});
  1. Modify webpack.config.jsthe configuration objects exposed to the outside in the file, and add the following configuration nodes:
module.exports = {
    
    
    plugins: [htmlPlugin] // plugins 数组是 webpack 打包期间会用到的一些插件列表
}

2.6 Configure parameters related to automatic packaging

 // package.json中的配置
 // --open 打包完成后自动打开浏览器页面
 // --host 配置 IP 地址
 // --port 配置端口
 "scripts": {
    
    
     "dev": "webpack-dev-server --open --host 127.0.0.1 --port 8888"
 },

3. webpackLoader in

3.1 By loaderpackaging non- jsmodules

In the actual development process, webpackonly .jsmodules ending with the suffix name can be packaged and processed by default . Other .jsmodules that webpackdo not end with the suffix name cannot be processed by default. The loaderloader needs to be called to package normally, otherwise an error will be reported!

loaderThe loader can assist in webpackpackaging and processing specific file modules, such as:

  • less-loaderCan package and process .lessrelated files
  • sass-loaderCan package and process .scssrelated files
  • url-loaderIt can be packaged deal csswith urlfile-related paths

3.2 loadercall process

webpackThe basic use of the loader in 3.3

3.3.1 Package processing cssfile

  1. Run the npm i style-loader css-loader -Dcommand, install and processcss 文件的 loader
  2. In webpack.config.jsthe module -> rulesarray, the loaderrules for adding are as follows:
// 所有第三方文件模块的匹配规则
module: {
    
    
    rules: [
        {
    
     test: /\.css$/, use: ['style-loader', 'css-loader'] }
    ]
}

Among them, testindicates the matching file type, useindicates the corresponding file to be called, loaderand executes from back to front

Note :

  • useThe loaderorder specified in the array is fixed
  • loaderThe order of multiple calls is: call from back to front

3.3.2 Package processing lessfile

  1. Run npm i less-loader less -Dcommand
  2. In webpack.config.jsthe module -> rulesarray, the loaderrules for adding are as follows:
 // 所有第三方文件模块的匹配规则
 module: {
    
    
     rules: [
         {
    
     test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] }
     ]
 }

3.3.3 Package processing scssfile

  1. Run npm i sass-loader node-sass -Dcommand
  2. In webpack.config.jsthe module -> rulesarray, the loaderrules for adding are as follows:
 // 所有第三方文件模块的匹配规则
 module: {
    
    
     rules: [
         {
    
     test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'] }
     ]
 }

3.3.4 Configure postCSSautomatically added csscompatible prefix

  1. Run npm i postcss-loader autoprefixer -Dcommand
  2. Create postcssa configuration file in the project root directory postcss.config.jsand initialize the following configuration:
const autoprefixer = require('autoprefixer') // 导入自动添加前缀的插件
module.exports = {
    
    
    plugins: [autoprefixer] // 挂载插件
}
  1. In webpack.config.jsthe module -> rulesarray, modifying cssthe loaderrules are as follows:
module: {
    
    
    rules: [
        {
    
     test: /\.css$/, use: ['style-loader', 'css-loader', 'postcss-loader'] }
    ]
}

3.3.5 Pack the pictures and font files in the style sheet

  1. Run npm i url-loader file-loader -Dcommand
  2. In webpack.config.jsthe module -> rulesarray, the loaderrules for adding are as follows:
module: {
    
    
    rules: [{
    
    
        test: /\.jpg|png|gif|bmp|ttf|eot|svg|woff|woff2$/,
        use: 'url-loader?limit=16940'
    }]
}

Note :

  • Which ?is after the loaderparameter entry
  • limitUsed to specify the size of the picture, the unit is byte ( byte), only limitpictures smaller than the size will be converted to base64pictures

3.3.6 jsAdvanced syntax in package processing file

  1. Install babelconverter-related packages:npm i babel-loader @babel/core @babel/runtime -D
  2. Install babelthe packages related to the syntax plugin:npm i @babel/preset-env @babel/plugin-transformruntime @babel/plugin-proposal-class-properties –D
  3. In the project root directory, create a babelconfiguration file babel.config.jsand initialize the basic configuration as follows:
module.exports = {
    
    
    presets: ['@babel/preset-env'],
    plugins: ['@babel/plugin-transform-runtime', '@babel/plugin-proposalclass-properties']
};
  1. In webpack.config.jsthe module -> rulesarray, the loaderrules for adding are as follows:
// exclude 为排除项,表示 babel-loader 不需要处理 node_modules 中的 js 文件
{
    
     test: /\.js$/, use: 'babel-loader', exclude: /node_modules/ }

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/110985579