Front-end and mobile development----webpack----plugin

webpack

aims:

  • Ability to extract css from the project into a separate file
  • Can use configuration to automatically import packaged resources into html
  • Can use clean-webpack-plugin to empty the package directory
  • Can do css code and js code compression optimization

Plugins are used to extend the functions of webpack. Various plugins can make webpack do almost anything related to construction.

E.g:

  • Extract css to a separate file
  • Empty the packaging directory
  • Automatically copy index.html to the target folder

The configuration of plugin is very simple. The plugins configuration item receives an array. Each item in the array is an instance of the plugin to be used. The parameters required by the plugin are passed in through the constructor.

The difficulty of using plugin lies in the configuration items of plugin itself, not how to introduce plugin into webpack. Almost all the functions that webpack cannot directly realize can be solved by open source plugin. What we have to do is to find more according to our needs Find the corresponding plugin.

format:

module.exports = {
   entry: 
   output:,
   module:,
   plugins:[] // 设置plugin
}

mini-css-extract-plugin

Function: This plug-in helps us extract the css code into a separate file (instead of embedding it in the html file in a style).

npm official website: https://www.npmjs.com/package/mini-css-extract-plugin

use:

  • Download and install
  • Configure webpack.config.js
  • Run webpack to package and check the effect

Download and install

It is a development dependency.

npm install mini-css-extract-plugin -D 
--------------------------------------
+ [email protected]
added 7 packages from 3 contributors in 10.363s

Configuration

In webpack.config.js, modify three places:

  • Introduce plugin
  • Add loader to less loader list
  • Add mini-css-extract-plugin in plugins

as follows:

// node 中的核心模块
const path = require('path')

const MiniCssExtractPlugin = require('mini-css-extract-plugin')

module.exports = {
    
    
  //
  {
    
    
        test: /\.less$/,  // 如果这个模块以less结尾
        // 如果在打包的过程遇到了.less,则:从右向左
        // 1. 先用less-loader 读出内容,转成css
        // 2. 用css-loader 读出内容
        // 3. 用postcss-loader 配合autoprefixer这个工具给需要前缀的样式添加前缀
        // 4. style-loader把读出的内容以style标签的格式
        // 附加在.html文件上
        // use: ['style-loader','css-loader', 'postcss-loader', 'less-loader'] // 设置要处理的loader
        use: [
          {
    
    
            loader: MiniCssExtractPlugin.loader,
            options:{
    
    publicPath: '../'}
          },
          'css-loader', 'postcss-loader', 'less-loader'
        ] // 设置要处理的loader
      },
        
  // ... 
  plugins:[
    new MiniCssExtractPlugin({
    
    
      filename:'css/[name].css'
    })
  ]
}

Give it a try.

Insert picture description here

Since the css is placed in a separate file at this time, if you want to introduce styles in index.html, you need to manually add a reference to css.

html-webpack-plugin

problem:

You need to manually import css, you need to manually copy index.html from the source folder to the target folder...

Both can be solved with html-webpack-plugin.

Function: Copy the .html file that we have written to the designated packaging export directory, and automatically introduce related resource codes .

Dynamically add the hash after each compile to the external resources introduced in the html file, such as script and link, to prevent the problem of referencing cached external files. Can generate and create html entry file.

Official website: https://www.npmjs.com/package/html-webpack-plugin

Implementation steps:

Download and install

npm i html-webpack-plugin -D
------------------------------------
+ [email protected]
added 63 packages from 130 contributors in 42.462s

Configuration

In webpack.config.js, do two things:

  1. Introduce plugin
const HtmlWebpackPlugin = require('html-webpack-plugin');
  1. Move index.html under src to pulbic/index.html
  2. Add a plugins configuration
// node 中的核心模块
const path = require('path')
// console.log( path.resolve('./src/index.html')  )

const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    
    
	// ...
  plugins:[
    new MiniCssExtractPlugin({
    
    
      filename:'css/[name].css'
    }),
    new HtmlWebpackPlugin({
    
    
      minify: {
    
     // 压缩HTML文件
        removeComments: true, // 移除HTML中的注释
        collapseWhitespace: true, // 删除空白符与换行符
        minifyCSS: true// 压缩内联css
      },
      filename: 'index.html',
      // path.resolve()就是转成绝对路径
      template: path.resolve('./public/index.html') // 指定模块的位置
    })
  ]
}
  1. Package test

    • It will copy (compress) the .html file specified in the template to the export folder
    • The packaged .css and .js code will also be automatically attached

Schematic diagram:

Insert picture description here

clean-webpack-plugin

Before generating the package file, clear the export directory.

installation

npm i clean-webpack-plugin -D

Modify the configuration file webpack.config.js

  1. Introduce:

    const {
          
           CleanWebpackPlugin } = require('clean-webpack-plugin')
    
  2. Add plugins

plugins:[
        new CleanWebpackPlugin(),
        其它...
]

When packaging again, it will help us delete the export folder first, if it prompts that there is no permission:

Error: EPERM: operation not permitted, lstat 'D:\webpack-learn\02-code\webpack-dev-111\build\css\main.css'
    at Object.lstatSync (fs.js:1033:3)

You can try:

  • Run the packaging command in the terminal of vscode
  • Apple this:sudo npx webpack
  • window: When opening powershell,Insert picture description here

Code compression optimization

Remember to set the packaging method to生产模式:mode: 'production'

  • Compress css

    1. Install plugin
    npm i -D optimize-css-assets-webpack-plugin
    
    1. Configure plugins

      const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')
      
      module.exports= {
              
              
      	optimization: {
              
              
          minimizer: [
            new OptimizeCssAssetsWebpackPlugin()
            ]
      	}
      }
      
      
  • Remove the console.log in the js code

const TerserWebpackPlugin = require('terser-webpack-plugin')

module.exports = {
    
    
   // ...
+  optimization: {
    
    
    minimizer: [
      // new OptimizeCssAssetsWebpackPlugin(),
      new TerserWebpackPlugin({
    
    
        parallel: 4,
        extractComments: true,
        terserOptions: {
    
    
          compress: {
    
    
            warnings: false,
            drop_console: true,
            drop_debugger: true
          }
        }
      })
    ]
  },
}

summary

Plugins are used to increase webpack capabilities.

step:

  1. Download and install
  2. Configure webpack.config.js
    1. Introduce
    2. Add plugins settings

If there are any shortcomings, please advise, to
be continued, continue to update!
Make progress together!

Guess you like

Origin blog.csdn.net/qq_40440961/article/details/112954618