Detailed explanation of webpack.config.js configuration file

1. Packaging style resources (using loader)

webpack can only process js/json resources, so the packaging of style resources needs to be passed loader, and loaderneeds webpack.config.jsto be defined in the (webpack configuration file)

The webpack.config.jsconfiguration file is used to indicate what operations webpack needs to do. When the webpack command is run, the configuration items inside will be loaded, and the configuration file syntax uses commonjs. The reason is: all the build tools are based on the nodejs platform. Nodejs modularization uses commonjs by default, which is different from .jsthe es6 syntax used by js source files in the project.

Project structure:

bulid

src

​ index.js

​ index.css

webpacl.config.js

webpack.config.jsstructure:

// resolve用来拼接绝对路径
const {
    
     resolve } = require('path');

module.exports = {
    
    
    // webpack配置
    // 入口起点
    entry: './src/index.js',
    // 输出
    output: {
    
    
        // 输出文件名
        filename: 'main.js',
        // 输出路径
        // 表示输出到当前文件所属目录下的bulid目录
        path: resolve(__dirname,'bulid')
    },
    // loader的配置
    module: {
    
    
        rules:[
            // 详细loader配置
        ]
    },
    // plugins配置
    plugins: [
        // 详细plugins的配置
    ],
    // 模式 表明此时是开发者模式
    mode: 'development',
}

loaderConfiguration (css resource packaging configuration):

module: {
    
    
        rules:[
            // 详细loader配置
            {
    
    
                // 匹配哪些文件
                // 此处表示匹配以.css结尾的文件
                test: /\.css$/,
                // 使用哪些loader进行处理
                use: [
                    // use数组loader执行顺序:从右到左,从下到上,依次执行,也即先执行css-loader,再执行style-loader
                    // 创建style标签,将js中的样式资源(上一部分所形成的样式字符串)插入到style标签中,添加到head中
                    'style-loader',
                    // 将css文件变成commonjs模块加载在js中,里面内容是样式字符串
                    'css-loader'
                ]
            }
        ]
    }

Note: The loader mentioned above needs to be downloaded before use:npm i -s style-loader css-loader

Execute packaging, because the configuration file is added, the webpackpackaging can be carried out by executing the input

Note: Different files must be processed by different loader

Therefore, the processing configuration for less files is:

Download the package first:, npm i -s style-loader css-loader less-loader lessbecause less-loader depends on less, so also download less, otherwise an error will be reported

module: {
    
    
        rules:[
            // 处理css文件
            {
    
    
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            },
            // 处理less文件
            {
    
    
                test: /\.less$/,
                use: [
                    'style-loader',
                    'css-loader',
                    // 将less文件编译成css文件
                    'less-loader'
                ]
            }
        ]
    }
2. Package html resources (using plugins)

The packaging configuration of html resources can be configured using plugins. Unlike loader configuration (download loader first, then use loader), plugins configuration has three steps, namely:

  • download

    npm i html-webpack-plugin -D
    

    Where -D means download in developer mode

  • Introduce

    const htmlWebpackPlugin = require('html-webpack-plugin')
    
  • use

    Since it htmlWebpackPluginis a constructor, it is called by creating an instance

    plugins: [
          new htmlWebpackPlugin();
        ],
    

    If it is only called in the above way, the actual function is: by default, an empty html file (without any style js) will be created, and all the resources (JS/CSS/pictures...) that are packaged and output will be automatically imported.

    However, under normal circumstances, a structured html file is required, so the following configuration is adopted

    plugins: [
          new htmlWebpackPlugin({
          
          
              template: './src/index.html',
              filename: 'main.html'// 指定输出文件名
          });
        ],
    

    The function of the above configuration is: ./src/index.htmlfill in empty html files, and automatically import all the resources (js/css/pictures...) that are packaged and output.

    Note: Since the packaged html will automatically introduce all the resources of the packaged output, it is not necessary ./src/index.htmlto re-import it as a template , otherwise it may be prone to unexpected errors

3. Pack image resources
  • The picture is introduced in the style file, but the picture does not exist in the html file

    css

    .box1 {
          
          
        width: 200px;
        height: 200px;
        background-image: url(../imgs/1.PNG);
        background-repeat: no-repeat;
    }
    
    .box2 {
          
          
        width: 300px;
        height: 200px;
        background-image: url(../imgs/2.PNG);
        background-repeat: no-repeat;
    }
    
    .box3 {
          
          
        width: 400px;
        height: 200px;
        background-image: url(../imgs/3.PNG);
        background-repeat: no-repeat;
    }
    
    const {
          
           resolve } = require('path');
    
    const htmlWebpackPlugin = require('html-webpack-plugin');
    
    // console.log();
    
    module.exports = {
          
          
      entry: './src/index.js',
      output: {
          
          
        filename: 'bulid.js',
        path: resolve(__dirname,'bulid')
      },
      module: {
          
          
        rules: [
          {
          
          
            test: /\.less$/,
            use: [
              'style-loader',
              'css-loader',
              'less-loader'
            ]
          },
          {
          
          
            test: /\.css$/,
            use: [
              'style-loader',
              'css-loader'
            ]
          },
          {
          
          
            // 处理图片资源 严格区分大小写 url-loader对图片路径引入的处理
            test: /\.(PNG|jpg|gif)$/,
            // 使用单个loader采用loader声明,使用多个loader采用use处理
            // 由于url-loader依赖于file-loader 因此下载url-loader 也需要下载file-loader
            loader: 'url-loader',
            options: {
          
          
              // 图片大小小于8kb,就会被base64处理
              // 优点:减少请求数量,减轻服务器压力
              // 缺点:图片体积会更大,导致文件请求速度变慢,所以不是所有的图片大小都适合base64处理,一般处理小于8kb~12kb的图片
              limit: 8 * 1024
            }
          }
        ]
      },
      plugins: [
        new htmlWebpackPlugin({
          
          
          template: './src/webpack_02.html',
          filename: 'index.html'
        })
      ],
      mode: 'development'
    }
    

    Packing result:

    Pictures smaller than 8kb are base64 encoded, pictures larger than 8kb are packaged, the picture name is a unique hash value generated according to the current picture, and for the same picture, webpack will not process it repeatedly, but will only pack it once

    But under normal circumstances, the image will be imported in the html tag, and the image will be imported in the html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>hhhh</title>
    </head>
    <body>
    <div class="box1">1</div>
    <div class="box2">2</div>
    <div class="box3">3</div>
    <img src="./imgs/2.PNG" alt="2.PNG">
    </body>
    </html>
    

    Still use the above configuration for packaging processing, the result: the img->src in the html file is still the same, and the image cannot be displayed in the browser. Reason: there is no ./imgs/2.PNGimage resource in the index.html directory after packaging , so you can see the above configuration It can't process image resources in html, but can only process image resources introduced by css/less . Solve:

  • Process images introduced in html:

    Add to:html-loader

    // 此处只展示loader部分,原因:新增内容只在loader中
      module: {
          
          
        rules: [
          {
          
          
            test: /\.less$/,
            use: [
              'style-loader',
              'css-loader',
              'less-loader'
            ]
          },
          {
          
          
            test: /\.css$/,
            use: [
              'style-loader',
              'css-loader'
            ]
          },
          {
          
          
            // 处理图片资源 严格区分大小写
            test: /\.(PNG|jpg|gif)$/,
            // 使用单个loader采用loader声明,使用多个loader采用use处理
            // 由于url-loader依赖于file-loader 因此下载url-loader 也需要下载file-loader
            loader: 'url-loader',
            options: {
          
          
              // 图片大小小于8kb,就会被base64处理
              // 优点:减少请求数量,减轻服务器压力
              // 缺点:图片体积会更大,导致文件请求速度变慢,所以不是所有的图片大小都适合base64处理,一般处理小于8kb~12kb的图片
              limit: 8 * 1024
            }
          },
          {
          
          
            test: /\.html$/,
            // 处理html文件中的img图片(负责引入img,从而能被url-loader进行处理)
            loader: 'html-loader'
          }
        ]
      }
    

    After configuring the file, package it again, and the result is as follows:

    img tag:

    <img src="3e4643f01f5a182ea427.PNG" alt="2.PNG">
    

    But after double-clicking and packaging, the 3e4643f01f5a182ea427.PNGpicture cannot be displayed, and an error message is displayed:, image not loaded Try to open it externally to fix format problemwhile the browser is opened index.html, the picture still cannot be displayed. The reason is: url-loader uses es6 modular analysis by default, and html-loader uses commonjs to import pictures. Modular parsing. Different parsing causes problems. Solution: Turn off the es6 modularization of url-loader and use comonjs parsing. For webpack5, you also need to turn off es6 modularization in html-loader

     {
          
          
            // 处理图片资源 严格区分大小写
            test: /\.(PNG|jpg|gif)$/,
            // 使用单个loader采用loader声明,使用多个loader采用use处理
            // 由于url-loader依赖于file-loader 因此下载url-loader 也需要下载file-loader
            loader: 'url-loader',
            options: {
          
          
              // 图片大小小于8kb,就会被base64处理
              // 优点:减少请求数量,减轻服务器压力
              // 缺点:图片体积会更大,导致文件请求速度变慢,所以不是所有的图片大小都适合base64处理,一般处理小于8kb~12kb的图片
              limit: 8 * 1024,
              esModule: false,
              // 给图片重命名 [hash:10]取图片的hash的前10位 [ext]取文件原来扩展名
              name: '[hash:10].[ext]'
            }
          },
          {
          
          
            test: /\.html$/,
            // 处理html文件中的img图片(负责引入img,从而能被url-loader进行处理)
            loader: 'html-loader',
            options: {
          
          
              esModule: false
            }
          }
    

    Final result: full display picture

  • Package other resources

    module: {
          
          
      rules: [
        {
          
          
          test: /\.css$/,
          use: ['style-loader','css-loader']
        },
        // 打包其他资源(除了html js css 资源以外的资源)其他资源是指:已配置处理的资源之外的没有处理的资源
        {
          
          
          // 排除css html js 以为的资源 
          exclude: /\.(css|html|js)$/, // 或者写成:test: \./(xx|xxx)$\采用此方式需要一个一个匹配
          loader: 'file-loader'
        }
      ]
    },
    

Guess you like

Origin blog.csdn.net/chen__cheng/article/details/115196091