preface

Original intention: share a few practical plugins in the work, hope to everyone some help, do not like spray.

html-webpack-plugin

Purpose: Package a page template to dist directory, default is automatically imported JS or CSS

The installation

cnpm i html-webpack-plugin@3.2. 0 -D
Copy the code

configuration

index.html

<! DOCTYPEhtml>
<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>Home page</title>
</head>
<body>
    <div id="app"></div>
</body>
</html>
Copy the code

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    plugins: [
        new HtmlWebpackPlugin({
            template: './index.html'.// Use our local index.html file as the base template
            filename: "index.html".// The name of the file output to the dist directory]}}),Copy the code

HtmlWebpackPlugin takes an object and configes it itself. See here for details

clean-webpack-plugin

Purpose: For each package dist directory delete

The installation

cnpm i clean-webpack-plugin -D
Copy the code

configuration

webpack.config.js

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

extract-text-webpack-plugin

This plugin only supports versions prior to WebPack4. If you are currently in WebPack4 or later, you will get an error.

The installation

cnpm i extract-text-webpack-plugin -D
Copy the code

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}})]Copy the code

The above configuration, extractTextPlugin. Extract parameters inside fallback is when extraction is not successful, will perform style – loader. If allChunks is set to false, only the initialized CSS file is extracted. If true, the asynchronous CSS file is extracted.

mini-css-extract-plugin

Use: This plugin is the same as the exract-text-webpack-plugin, which extracts CSS styles. The only difference is the use of this plugin, which is recommended after The WebPack4 version

The installation

cnpm i mini-css-extract-plugin -D
Copy the code

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"}})]Copy the code

In the configuration above, you can see that the usage of the exract-text-webpack-plugin is different. Take a look at the differences.

  1. loaderConfiguration is notfallback
  2. inpluginSet in thefilenameLoad resource names synchronously, and also specify asynchronous loadingcssresourceschunkFilename
  3. The plug-in supports configurationpublicPathUsed to set asynchronous loadingcssThe path of the
  4. exract-text-webpack-pluginOnly one CSS file will be extracted,mini-css-extract-pluginWill be extracted from the asynchronous file.

webpack.optimize.CommonsChunkPlugin

Purpose: Used to extract common code from a page to optimize load speed, CommonsChunkPlugin is only supported before Webpack4.

The installation

The plug-in is built into Webpack and does not require installation.Copy the code

configuration

main.js

import Vue from "vue"
Copy the code

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"}})]Copy the code

In the above configuration, we extract the Vue. Js file from main.js and its dependency files for optimization, so as to avoid loading the JS file every time we package or visit another page. We first extract the Vue base environment, because it hardly changes, so the extraction optimization is necessary. Then the Webpack runtime code is also extracted, so that the vendor will be packaged again without change, can go to the browser cache

optimization.SplitChunks

Purpose: the function like the webpack.optimize.Com monsChunkPlugin above, optimization. The only webpack4 SplitChunks is recommended

The installation

Built-in, no installation required.Copy the code

configuration

main.js

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

news.js

import Vue from "vue"
console.log(Vue)
Copy the code

webpack.config.js

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

In the preceding configuration, the splitChunks are set to all and are valid for all chunks. By default, only async asynchronous chunks are valid.

By default, splitChunks are automatically extracted. The default requirements are as follows:

  • The extracted module is fromnode_moduledirectory
  • The module is larger than 30KB
  • The maximum number of resources requested during on-demand loading is less than or equal to 5
  • The maximum number of concurrent requests during the first load is less than or equal to 3

DefinePlugin

Purpose: Used to inject global variables. Usually used on environment variables.

The installation

No installation required, webPack is built-inCopy the code

configuration

webpack.config.js

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

In the above configuration, DefinePlugin receives an object with a key value corresponding to a value. The value is a code snippet. If you look at the name above, the error is “is not defined”.

ProvidePlugin

Purpose: to define global variables, such as 100 pages to introduce vue, each page will only add work, just mount a variable in webpackProvide, do not have to import each one.

The installation

No installation required, webPack is built-inCopy the code

configuration

webpack.config.js

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

In the above configuration, ProvidePlugin receives an object, the key value is the variable to use, the first parameter of the value is the Vue Module, and the second parameter takes the property of Es Module.default by default. Import is an Es Module object that has the default attribute and is an entity object

hot-module-replacement-plugin

Purpose: Enable hot module update

The installation

No installation required, webPack is built-inCopy the code

configuration

webpack.config.js

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

IgnorePlugin

Purpose: Used to filter package files and reduce the package size.

The installation

No installation required, webPack is built-inCopy the code

configuration

webpack.config.js

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

uglifyjs-webpack-plugin

Purpose: Used to compress JS files, webPack4 or later.

The installation

cnpm install uglifyjs-webpack-plugin -D
Copy the code

configuration

webpack.config.js

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

copy-webpack-plugin

Purpose: Used to copy files to a directory

The installation

cnpm i  copy-webpack-plugin@6.41. -D
Copy the code

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"}}}Copy the code

In the configuration above, copy main.js to js in dist directory. The default toType is file, or set it to dir, because I don’t have js directory in dist directory.

optimize-css-assets-webpack-plugin

Purpose: To compress CSS styles

The installation

cnpm i optimize-css-assets-webpack-plugin -D
Copy the code

configuration

webpack.config.js

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

imagemin-webpack-plugin

Purpose: Compression image applications

The installation

cnpm i imagemin-webpack-plugin -D
Copy the code

configuration

webpack.config.js

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

friendly-errors-webpack-plugin

Purpose: beautify console, good prompt error,. We don’t want to mess up our terminal startup, like this

The installation

cnpm i friendly-errors-webpack-plugin -D
Copy the code

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: [' Hello frogman, the system is running at http://localhost:' + devserver. port]}, clearConsole: true,})], devServer}Copy the code

Run the above code. Look at the results

Thank you

Thank you for reading this article. I hope it helps you. If you have any questions, please correct me.

✿ Theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus

Interested partners can join [front end entertainment circle exchange group] welcome everyone to exchange and discuss

Writing is not easy, “like” + “watching” + “retweet” thanks for supporting ❤

Past oliver

How to write a Vue component and publish it to NPM

Sharing 12 Common Webpack Loaders

What are CommonJs and Es Modules and how they differ?

Maps to Understand Data Structures with Ease

Do you know all these JavaScript Tricks for work?

【 Suggestions 】 Share some Git commands commonly used in work and how to solve special problems

Do you really understand the functional features in ES6?