Share 15 useful plugins for Webpack! ! !

Preface

Original intention: to share some useful things in work Plugin, I hope it will be of some help to everyone, don't like it.

html-webpack-plugin

Purpose: Pack a page template into the dist directory, and by default it will automatically import js or css

installation

cnpm i html-webpack-plugin@3.2.0 -D

Configuration

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>首页</title>
</head>
<body>
    <div id="app"></div>
</body>
</html>

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    
    
    plugins: [
        new HtmlWebpackPlugin({
    
    
            template: './index.html',  // 以咱们本地的index.html文件为基础模板
            filename: "index.html",  // 输出到dist目录下的文件名称
        }),
    ]
}

HtmlWebpackPluginReceive an object, configure it yourself, see here for details

clean-webpack-plugin

Purpose: used to delete every package dist directory

installation

cnpm i clean-webpack-plugin -D

Configuration

webpack.config.js

const {
    
     CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
    
    
    plugins: [
        new CleanWebpackPlugin()
    ]
}

extract-text-webpack-plugin

Purpose: Extract the cssstyle from the jsfile and finally synthesize a cssfile. The plug-in only supports the webpack4previous version. If you are currently at webpack4or above the version, an error will be reported.

installation

cnpm i extract-text-webpack-plugin -D

Configuration

webpack.config.js

const extractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
    
    
    module: {
    
    
        rules: [
            {
    
    
                test: /\.css$/,
                use: extractTextPlugin.extract({
    
    
                    fallback: "style-loader", 
                    use: "css-loader"
                })
            }
        ]
    },
    plugins: [
        new extractTextPlugin({
    
    
            filename: "[name].css",
            allChunks: true
        })
    ]
} 

In the above configuration, the extractTextPlugin.extractparameters inside fallbackare executed when the extraction is unsuccessful style-loader. useWhich is used to extract css-loaderthe conversion, pluginswhich configuration filenameis finally finished merging .cssthe file name, when allChunksis falsethe time, only when extracting initialization cssfile for trueextracts when asynchronous cssfile.

mini-css-extract-plugin

Purpose: The plug-in is exract-text-webpack-pluginthe same as the above , it extracts the css style, the only difference is the usage, webpack4it is recommended to use it after the version of the plug-in

installation

cnpm i mini-css-extract-plugin -D

Configuration

webpack.config.js

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
    
    
    module: {
    
    
        rules: [
            {
    
    
                test: /\.css$/,
                use: [
                   MiniCssExtractPlugin.loader,
                   "css-loader"
                ]
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
    
    
            filename: "css/[name].css",
            chunkFilename: "css/[name].css"
        })
    ]
} 

In the above configuration, you can see the usage and the exract-text-webpack-plugindifference, let's take a look at the difference.

  1. loaderNo configurationfallback
  2. In pluginsetting filenamethe synchronization load the resource name, also specify asynchronous loading cssof resourceschunkFilename
  3. The plug-in supports configuration publicPathto set cssthe path of asynchronous loading
  4. exract-text-webpack-pluginOnly one css file will be extracted, and it mini-css-extract-pluginwill be extracted based on the asynchronous file.

webpack.optimize.CommonsChunkPlugin

Purpose: Used to extract the common code in the page, so as to optimize the loading speed, this CommonsChunkPluginonly supports the Webpack4previous.

installation

该插件是Webpack内置的,不需要安装。

Configuration

main.js

import Vue from "vue"

webpack.config.js

module.exports = {
    
    
    entry: {
    
    
        main: "./main.js",
        vendor: ["Vue"]
    },
    plugins: [
        new Webpack.optimize.CommonsChunkPlugin({
    
    
            name: "vendor",
            filename: "[name].js"
        }),
        new Webpack.optimize.CommonsChunkPlugin({
    
    
            name: "common",
            chunks: ["vendor"],
            filename: "[name].js"
        })
    ]
}

In the above configuration, we extract and optimize main.jsthe dependent files in Vue.jsit to avoid loading this jsfile every time you package or visit other pages . We first Vueextract the basic environment, because the basic environment will hardly change , So that extraction optimization is necessary. Then Webpackextract the runtime code, so that vendorit won’t change if you package it again, you can use the browser cache

optimization.SplitChunks

Purpose: This function is the webpack.optimize.CommonsChunkPluginsame as above , but it optimization.SplitChunksis webpack4recommended to use later

installation

内置的,不需要安装。

Configuration

main.js

import Vue from "vue"
console.log(Vue)
import("./news")

news.js

import Vue from "vue"
console.log(Vue)

webpack.config.js

module.exports = {
    
    
    mode: "development",
    entry: {
    
    
        main: "./main.js"
    },
    output: {
    
    
        filename: "[name].js",
        path: __dirname + "/dist"
    },
    optimization: {
    
    
        splitChunks: {
    
    
            chunks: "all"
        }
    },
}

In the above configuration, splitChunksthe chunksas allis all chunktake effect by default only asyncvalid asynchronous.

splitChunksThere is also automatic extraction by default, and the default requirements are as follows:

  • The extracted modules are from the node_modulecatalog
  • Module is larger than 30kb
  • When loading on demand, the maximum requested resource is less than or equal to 5
  • The maximum number of parallel requests at the first load is less than or equal to 3

DefinePlugin

Purpose: Used to inject global variables, generally used in environment variables.

installation

无需安装,webpack内置

Configuration

webpack.config.js

const Webpack = require("webpack")
module.exports = {
    
    
    plugins: [
        new Webpack.DefinePlugin({
    
    
           STR: JSON.stringify("蛙人"),
           "process.env": JSON.stringify("dev"),
            name: "蛙人"
        })
    ]
}

In the above configuration, DefinePluginan object is received, and the keyvalue inside corresponds to a valuevalue. This valuevalue is a code snippet. You can see the above one name, and an error will be reported 蛙人 is not defined. Please note here that the valuevalue must be a variable or a code snippet .

ProvidePlugin

Purpose: Used to define global variables, such as importing 100 pages, importing vueeach page will only increase the workload, just webpackProvidemount a variable directly , no need to import one by one.

installation

无需安装,webpack内置

Configuration

webpack.config.js

const Webpack = require("webpack")
module.exports = {
    
    
    plugins: [
        new Webpack.ProvidePlugin({
    
    
            "Vue": ["vue", "default"] 
        })
    ]
}

In the above configuration, ProvidePluginan object keyis received, the value is the variable used, the valuefirst parameter of the value is the Vuemodule, and the second parameter is the default Es Module.defaultattribute. importThe default is the introduction of a coming Es Moduleobject, which has defaultthis property is the entity object

hot-module-replacement-plugin

Purpose: open hot module update

installation

无需安装,webpack内置

Configuration

webpack.config.js

const Webpack = require("webpack")
module.exports = {
    
    
    plugins: [
        new Webpack.HotModuleReplacementPlugin()
    ]
}

IgnorePlugin

Purpose: Used to filter packaged files and reduce the size of packaged files.

installation

无需安装,webpack内置

Configuration

webpack.config.js

const Webpack = require("webpack")
module.exports = {
    
    
    plugins: [
        new Webpack.IgnorePlugin(/.\/lib/, /element-ui/)
    ]
}

uglifyjs-webpack-plugin

Purpose: Used to compress jsfiles, aiming at webpack4versions and above.

installation

cnpm install uglifyjs-webpack-plugin -D

Configuration

webpack.config.js

const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
    
    
	optimization: {
    
    
        minimizer: [
            new UglifyJsPlugin({
    
    
                test: /\.js(\?.*)?$/i,
                exclude: /node_modules/
            })
        ]
    }
}

copy-webpack-plugin

Purpose: used to copy files to a directory

installation

cnpm i  copy-webpack-plugin@6.4.1 -D

Configuration

webpack.config.js

const CopyWebpackPlugin=require('copy-webpack-plugin');
module.exports = {
    
    
    plugins: [
        new CopyWebpackPlugin({
    
    
            patterns: [
                {
    
    
                    from: "./main.js",
                    to: __dirname + "/dist/js",
                    toType: "dir"
                }
            ]
        })
    ]
}

In the above configuration, will be main.jscopied to the distdirectory js, the toTypedefault filemay be set to dir, because my distno directory jscatalog.

optimize-css-assets-webpack-plugin

Purpose: Used to compress css style

installation

cnpm i optimize-css-assets-webpack-plugin -D

Configuration

webpack.config.js

const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin")
module.exports = {
    
    
    plugins: [
        new OptimizeCssAssetsWebpackPlugin(),
    ]
}

imagemin-webpack-plugin

Purpose: used to compress pictures

installation

cnpm i imagemin-webpack-plugin -D

Configuration

webpack.config.js

const ImageminPlugin =  require('imagemin-webpack-plugin').default
module.exports = {
    
    
    plugins: [
        new ImageminPlugin({
    
    
             test: /\.(jpe?g|png|gif|svg)$/i 
        })
    ]
}

friendly-errors-webpack-plugin

Purpose: to beautify the console, to prompt errors well. We don’t want our terminal to start up messy, like this

Example

installation

cnpm i friendly-errors-webpack-plugin -D

Configuration

webpack.config.js

const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
const devServer =  {
    publicPath: "/",
    port: 9527,
    host: "localhost",
    open: true,
    hotOnly: true,
    stats: 'errors-only'
}
module.exports = {
	plugins: [
		new FriendlyErrorsWebpackPlugin({
			compilationSuccessInfo: {
                notes: ['蛙人你好,系统正运行在http://localhost:' + devServer.port]
            },
            clearConsole: true,
		})
	],
	devServer
}

After running the above code. See the following results

thank

Thank you for reading this article. I hope it will be helpful to you. If you have any questions, please correct me.

I’m a frogman (✿◡‿◡), if you think it’s ok, please like it ❤.

Writing is not easy, "Like" + "Watching" + "Repost" Thank you for your support❤

Good articles in the past

"Teach you how to write a Vue component to publish to npm and it can be used outside the chain"

"Share 12 commonly used Loaders in Webpack"

"Talk about what are CommonJs and Es Module and their difference"

"Map that takes you easily to understand the data structure"

"Do you know all the JavaScript tips used in these jobs?"

"[Recommended Collection] Share some commonly used Git commands in work and how to solve special problem scenarios"

"Do you really understand the features of ES6?

Guess you like

Origin blog.csdn.net/weixin_44165167/article/details/115295155