webpack series one: basic configuration

Foreword:

I have nothing to do recently, and I wanted to learn more about the packaging tool webpack, so I found a course in Silicon Valley on the beep station, and followed it up. The articles I wrote are also some of my own learning experience. Share with everyone, if there is something inappropriate, please point it out in time, and I will definitely correct it. The update iteration of the front end is very fast. I hope that everyone will continue to learn new technologies to arm themselves.
First of all, we are here to introduce webpack, so we must first put the official website address of webpack: webpack Chinese website
Then, I said, I used the Shang Silicon Valley tutorial, and the following is the link address of the course: webpack5 from entry to proficiency --- --- webpack4 tutorial

introduce

  • Construction tools: When we write code on the front end, we always use some technologies that cannot be recognized by browsers such as ES6, less, sass, etc. At this time, we need to use some compilation tools to compile and build the code. The tool is a product that integrates these compilation tools.
  • Webpack packaging steps:
    – ① First, an entry file will be found, and packaging will start from this
    – ② Then, the required dependencies will be parsed out to form a dependency graph
    – ③ The required resources will be imported according to the dependency graph to form a chunk( code block)
    – ④ process the chunk (code block) (compile and package), for example: less=>css, js(ES6)=>js – ⑤
    After the packaging is completed, output the bundle
  • command
    初始化包-package.json文件:npm init
    安装webpack:npm i webpack webpack-cli
    打包指令:webpack 入口文件路径 -o 出口文件路径 --mode=development/production
    node环境运行:node 文件路径
  • Five core concepts
    Entry: Specify the entry
    Output: Indicate where the packaged resource bundle is output and how to name it
    Loader (translator): process non-JS files into files that webpack can recognize
    Plugins (plugins): can do Some things that Loader can’t do, eg: packaging, compression, redefining variables, etc.
    Mode: specify the environment, there are two by default: dev, production
  • webpack.config.js file basic configuration
// resolve用来拼接绝对路径的方法
const {
    
     resolve } = require("path");

module.exports = {
    
    
    // 入口文件
    entry: './src/index.js',
    // 出口
    output: {
    
    
        // 输出文件名,这里要注意一定要带后缀
        // 入口文件的输出路径可以在这里进行配置:eg: "js/dist.js"
        filename: 'dist.js',
        // __dirname为nodejs的变量,代表当前文件的绝对路径
        // 这是所有文件的输出路径
        path: resolve(__dirname, 'build')
    },
    // loader配置
    module: {
    
    
        rules: [
            // 详细的loader配置
        ]
    },
    // plugins配置
    plugins: [
        // 详细的plugins配置
    ],
    // 模式
    mode: 'development'
    // mode: 'production'
}
  • Notes:
    – 1. webpack can handle js/json files, but not other files
    – 2. The production environment and development environment will convert ES6 modularization into browser-recognizable modularity
    – 3. The production environment will package the generated js Compress the file
    – 4. After the packaging is completed, a unique hash value will be generated, which can be used to name the file

1 Handling style resources

  • Required Loader
    – style-loader: Create a style tag, insert the style resource in js, add it to the head to take effect
    – css-loader: mainly convert the css file into a commonjs module and load it into the js file, the content is a style String
    – less-loader/sass-loader/stylus-loader: Convert the corresponding preprocessed style file into a css file
  • configuration code
// loader配置
module: {
    
    
    rules: [
        // 详细的loader配置
        {
    
    
            test: /\.css$/,
            use: [
                // use数组中loader执行顺序,从右到左,从上到下依次执行
                // 创建style标签,将js中的样式资源插入进来,添加到head中
                'style-loader',
                // 将css文件转换成一个commonjs模块,内容是样式字符串
                'css-loader'
            ]
        },
        {
    
    
            test: /\.less$/,
            use: [
                'style-loader',
                'css-loader',
                // 将less文件转换成css文件
                'less-loader'
            ]
        }
    ]
},
  • Note:
    1: The execution order in use is from right to left, and from bottom to top.
    2: The preprocessing style package needs to be downloaded when the preprocessing loader is used.
    3: Also pay attention to the version matching problem

2 Processing image resources

  • Required loader (webpack4.x)
    – url-loader:
    ------ Can only handle image resources introduced in css style files, but cannot handle images with img tags
    ------ By default, ES6 modularization is used for parsing
    ------ Depends on file-loader
    - file-loader: url-loader depends on it, it can be used to process other resources
    - html-loader:
    ------ Process images introduced in img tags in html Resources
    ------ Use commonjs modularization for parsing
  • Configuration code (webpack4.x)
{
    
    
    test: /\.(jpeg|jpg|png|gif)$/,
    // 使用单个loader
    loader: 'url-loader',
    options: {
    
    
	   // 这个是用来关闭es6模块化解析
       esModule: false,
       /**
         * 图片大小小于8kb,就会被base64处理
         * 优点:减少请求数量(减轻服务器负担)
         * 缺点:图片体积会增大(文件请求速度更慢)
        */
         limit: 8 * 1024,
        /**
          * 给图片进行重命名
          * [hash:10]:取图片的哈希值前十位	
          * [ext]:取文件原来的扩展名
         */
         name: '[hash:10].[ext]'
     },
    type: 'javascript/auto'//这个属性如果没有设置,则会生成两张图片(如果你的页面只引入了一张图片)
},
{
    
    
     // 处理html的img标签引入的图片资源
     test: /.html$/,
     loader: 'html-loader'
}
  • Configuration code (webpack5.x has built-in url-loader and file-loader)
{
    
    
     // 处理图片资源
      test: /\.(jpeg|jpg|png|gif)$/,
      type: 'asset',
      parser: {
    
    
      	// 处理小图片,下面是指小于10kb的图片将被转换成base64的格式
         dataUrlcondition: {
    
    
             maxSize:  10 * 1024    // 10kb
         }
      },
      generator: {
    
    
         filename: "images/[hash:10][ext][query]"
      }
}

3 Process other resources (font icons, audio and video, etc.)

  • webpack4.x
    – As mentioned above, webpack4.x uses file-loader to process other resources
{
    
    
     // 处理其他资源
	 // exclude是用来排除其他的文件资源
     exclude: /.(css|less|js|html|jpeg|jpg|png|gif)$/,
     loader: 'file-loader',
     options: {
    
    
        name: '[hash:10].[ext]'
     }
}
  • webpack5.x
{
    
    
     // 处理其他资源
      test: /\.(ttf|woff2?|mp3|mp4)$/,
      type: 'asset/resource',
      generator: {
    
    
         filename: "midia/[hash:10][ext][query]"
      }
}

4 Automatically clear the last packaged content

  • Principle: Clear the entire directory content of output.path before packaging, and then package
  • webpack4.x: need to use clear-webpack-plugin
  • webpack5.x: only need output.clean = true
    output: {
    
    
        // 输出文件名,这里要注意一定要带后缀
        filename: 'dist.js',
        // __dirname为nodejs的变量,代表当前文件的绝对路径
        path: resolve(__dirname, 'build'),
        // 自动清空上次打包内容
        clean: true
    }

5 Handling html resources

  • Required Plugins
    – html-webpack-plugin
    ------ Function: Create an empty HTML by default, and automatically import all resources packaged and output
    ------ Requirements: A structured HTML file
    ---- -- Note: loader only needs to be loaded and then used directly, while Plugins need to be loaded, imported and used
  • Configuration code
    – download instruction: npm i html-webpack-plugin
    – import plugin: const HtmlWebpackPlugin = require('html-webpack-plugin')
    – use plugin:
    plugins: [
        // 详细的plugins配置
        // 功能:默认会创建一个空的HTML,自动引入打包输出的所有资源
        // 需求:一个有结构的HTML文件
        new HtmlWebpackPlugin({
    
    
            // 复制'./src/index.html'文件,自动引入打包输出的所有资源(css/js)
            template: './src/index.html'
        })
    ]

6 eslint syntax check

6.1 webpack4.x

  • Required third-party library and loader
    – eslint: Eslint Chinese website
    – eslint-loader
    – eslint-config-airbnb-base/eslint-config-airbnb: This is a relatively mature js specification library on npm –
    eslint-plugin-import : The above library depends on this
  • code configuration
{
    
    
   test: /$\.js/,
   exclude: /node_modules/,
   loader: 'eslint-loader',
   options: {
    
    
      // 自动修复
      fix: true
   }
}
  • Notes:
    [email protected] version uses eslint-loader
    [email protected] version is to add "eslintConfig": {} configuration in the package.json file
    – eslint-config-airbnb contains a react.js Some plugins, eslint-config-airbnb-base does not contain
    – the path of the airbnb specification, github official website -> Open Source -> Repositories-Topics->javascript->airbnb
  • package.json file code increase
"eslintConfig": {
    
    
	"extends": "airbnb-base"
}

6.2 webpack5.x

  • Required third-party libraries and loaders
    – eslint: Eslint Chinese Network
    – eslint-webpack-plugin
  • code configuration
plugins: [
    // 我这是webpack5的写法,插件要引用
    new EslintWebpackPlugin({
    
    
    	// 这里是因为我把resolve解构出来了
        context: resolve(__dirname, 'src'),
        fix: true
    })
],
"eslintConfig": {
    
    
	"extends": "airbnb-base"
}
  • .eslintrc.js
module.exports = {
    
    
    // 解析选项
    parserOptions: {
    
    
    	// js版本
    	esmaVersion: 6,
    	sourceType: "module"
    },
    env: {
    
    
    	node: true, // 启用node全局变量
    	browser: true // 启用浏览器中全局变量
    },
    // 具体检查规则,优先于我们继承的规则
    rules: {
    
    
    	"no-var": 2
    },
    extends: "eslint:recommended"
}
  • Note:
    – The [email protected] version uses eslint-webpack-plugin
    – The [email protected] version is configured in .eslintrc.js. There are many ways to write it. You can refer to the official website

7 devServer

  • webpack4.x
// 与五大核心同级
devServer:{
    
    
     // 项目构建后的路径
     contentBase: resolve(__dirname, 'build'),
     // 启动gzip压缩
     compress: true,
     // 端口号
     port: 3000,
     // 自动打开浏览器
     open: true
}
  • webpack5.x
// 与五大核心同级
devServer:{
    
    
     // 启动服务器域名
     host: localhost
     // 端口号
     port: 3000,
     // 自动打开浏览器
     open: true
}

write at the end

Creation is not easy
, please note the source when
reposting

Guess you like

Origin blog.csdn.net/m0_56026872/article/details/128250121