Webpack is a powerful build tool, and its rich and flexible configuration makes it difficult to use. Webpack-related questions can often be asked in interviews. If you just use scaffolding such as VUe-CLI without a thorough study of Webpack, you may not be able to answer them. I’m sure some interviewers won’t be able to ask questions without in-depth knowledge. Maybe two people will talk about how to configure the import and export, common loader, plugin.

As a youtiao front-end for many years, I have not faced up to the knowledge related to Webpack, let alone the interview questions related to Webpack. This time, I plan to study webpack-related content and record the learning content into webpack series, hoping that those who do not know webpack can master it.

Common WebPack plug-ins

Previously we briefly introduced how to develop a WebPack plug-in, now let’s look at what plug-ins are commonly used in daily development

1, HtmlWebpackPlugin

Function: automatically generate HTML files according to template files, and automatically insert the output file JS into HTML, eliminating the need to manually update the version number trouble.

const HtmlWebpackPlugin = require('html-webpack-plugin')

new HtmlWebpackPlugin({
    template: './public/index.html'.filename: 'index.html'
})
Copy the code

2, CleanWebpackPlugin

Function: Used to clear the packaged output folder, just think if each packaged file has a different version number, do not clear the folder in time, then will not be bigger and bigger. This plug-in can help us to automatically clear, avoid manual operation.

const { CleanWebpackPlugin } = require('clean-webpack-plugin')

new CleanWebpackPlugin()
Copy the code

3, CopyWebpackPlugin

Copy files from one directory to another. This can be used for static files under public, such as JS files at the same level as HTML, which need not be compiled but need to be exported to dist

const CopyWebpackPlugin = require('copy-webpack-plugin')

new CopyWebpackPlugin([
    { from: 'public/*.js'.flatten: true},])Copy the code

4, webpack. DefinePlugin

Function: Defines the values of some variables and replaces them with values when packaging

new webpack.DefinePlugin({
    ISPRO: true
})
Copy the code

In JS

if (ISPRO) {
    console.log(true);
}
Copy the code

The package will be replaced by

if (true) {
    console.log(true);
}
Copy the code

5, MiniCssExtractPlugin

Effect: Pull CSS into a separate file, otherwise it will be inline in HTML

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

new MiniCssExtractPlugin({
    filename: '[name].css'
})
Copy the code

6, PurgeCSSPlugin

What it does: Delete unreferenced selectors and their styles, need to be configured to judge the reference files, such as HTML, JS. CSS tree-shaking. Note that duplicate selector styles are not removed, which is a task of compression.

const glob = require('glob-all');
const PurgeCSSPlugin = require('purgecss-webpack-plugin')

new PurgeCSSPlugin({
    paths: glob.sync([path.resolve(__dirname, 'public/*.html'), 
        path.resolve(__dirname, '*.js')] and {nodir: true})})Copy the code

7, webpack. ProvidePlugin

Function: configure the global module, avoid the trouble of introducing many times

new webpack.ProvidePlugin({
    _: 'lodash'
})
Copy the code

You can use _ in any JS without reintroducing it

console.log(_)
Copy the code

8 BundleAnalyzerPlugin.

Function: file analysis plug-in, can be used for packaged resource dependency and size analysis

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

new BundleAnalyzerPlugin({
    generateStatsFile: true
})
Copy the code

9 ImageminPlugin.

Purpose: Compress an image

const ImageminPlugin = require('imagemin-webpack-plugin').default

new ImageminPlugin({
    pngquant: {
        quality: '95-100'}})Copy the code

PS: Because the plug-in installation depends on the download of other files, the download may not be possible. You can try to switch to CNPM download and try different versions of the download.

10, CompressionPlugin

Effect: Enable transport compression, such as compression of resources to GZIP format. The server is required to cooperate.

const CompressionPlugin = require("compression-webpack-plugin");

new CompressionPlugin({
    // Gzip compression configuration
    test: /\.js$|\.html$|\.css/.// Match the file name
    threshold: 10240.// Compress data that exceeds 10KB
    deleteOriginalAssets: false.// Whether to delete the original file
})
Copy the code

11, webpack NoEmitOnErrorsPlugin

Function: No output in case of compilation error. For example, when we enable hot load development, correcting incorrect resource references will cause the page to report errors in real time. Configuring this plug-in can make compilations that encounter errors no longer output resource files, and the page will not update errors. The same is true for packaging, where errors are encountered and the output is skipped.

new webpack.NoEmitOnErrorsPlugin()
Copy the code

12, OptimizeCssAssetsPlugin

Action: Compressing CSS removes duplicate class name styles

const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');

new OptimizeCssAssetsPlugin({
    assetNameRegExp: /\.css$/g
})
Copy the code

13, UglifyJsPlugin

Function: Compress JS

const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

new UglifyJsPlugin()
Copy the code

14, webpack HotModuleReplacementPlugin

Function: hot loading plug-in, with hot loading Settings, improve development efficiency

new webpack.HotModuleReplacementPlugin()
Copy the code

15, TerserPlugin

Function: Compressed JS, compared with UglifyJsPlugin plug-in, can better handle ES6 syntax

const TerserPlugin = require('terser-webpack-plugin');

optimization: {
    minimize: true.minimizer: [
        new TerserPlugin({
            parallel: true]}}),Copy the code

16, optimization. SplitChunks

Function: Extract multi-entry public files to avoid repeated packaging. Or extract a module file (such as node_modules) and use the page cache to speed up page loading

optimization: {
   splitChunks: {
        chunks: 'all'.cacheGroups: {
            vendor: {
                test: /node_modules/,
                name: 'vendor'.minChunks: 1,}}}}Copy the code

The latter

In fact, each plug-in has its own rich configuration options, so HERE I just briefly listed its main features and minimal configuration. For a deeper understanding, go to the NPM home page of each plug-in and learn its configuration documentation. In the process of configuration, I also encountered different pits, mainly version problems, so here posted my configuration version and code, encountered problems can have a look.

webpack.config.js

const path = require('path');
const glob = require('glob-all');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const PurgeCSSPlugin = require('purgecss-webpack-plugin')
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const CompressionPlugin = require("compression-webpack-plugin");
const TerserPlugin = require('terser-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const ImageminPlugin = require('imagemin-webpack-plugin').default

module.exports = {
    mode: 'none'.entry: './index.js'.output: {
        filename: '[name]-[chunkhash:6].js'.path: path.resolve(__dirname, 'dist'),
        publicPath: '/'
    },
    module: {
        rules: [{test: /\.css$/,
                use: [
                    'style-loader'] {},test: /\.css$/,
                use: [{
                    loader: MiniCssExtractPlugin.loader,
                    options: {
                        esModule: false}},'css-loader'] {},test: /\.(png|jpg|gif)$/,
                use: [
                {
                    loader: 'url-loader'.options: {
                        limit: 1024}}]}]},plugins: [
        new HtmlWebpackPlugin({
            template: './public/index.html'.filename: 'index.html'
        }),

        new CleanWebpackPlugin(),

        new webpack.DefinePlugin({
            ISPRO: true
        }),
        
        new CopyWebpackPlugin([
            { from: 'public/*.js'.flatten: true},]),new MiniCssExtractPlugin({
            filename: '[name].css'
        }),

        new PurgeCSSPlugin({
            paths: glob.sync([path.resolve(__dirname, 'public/*.html'), 
                path.resolve(__dirname, '*.js')] and {nodir: true})}),new webpack.ProvidePlugin({
            _: 'lodash'
        }),

        new BundleAnalyzerPlugin({
            generateStatsFile: true
        }),

        // CNPM I [email protected] -d
        new ImageminPlugin({
            pngquant: {
                quality: '95-100'}}),new CompressionPlugin({
            // Gzip compression configuration
            test: /\.js$|\.html$|\.css/.// Match the file name
            threshold: 10240.// Compress data that exceeds 10KB
            deleteOriginalAssets: false.// Whether to delete the original file
        }),
        
        new webpack.NoEmitOnErrorsPlugin(),

        new OptimizeCssAssetsPlugin({
            assetNameRegExp: /\.css$/g
        }),
        
        // new webpack.HotModuleReplacementPlugin()

        // new UglifyJsPlugin()].optimization: {
        splitChunks: {
            chunks: 'all'.cacheGroups: {
                vendor: {
                    test: /node_modules/,
                    name: 'vendor'.minChunks: 1,}}},minimize: true.minimizer: [
            new TerserPlugin({
                parallel: true}}}),]Copy the code

package.json

{
    "name": "webpack-test"."version": "1.0.0"."description": ""."main": "index.js"."dependencies": {
        "lodash": "^ 4.17.20"
    },
    "devDependencies": {
        "clean-webpack-plugin": "^ 3.0.0"."compression-webpack-plugin": "^ 6.0.0"."copy-webpack-plugin": "^ 5.1.2." "."css-loader": "^ 5.0.1." "."file-loader": "^ 6.2.0"."glob-all": "^ 3.2.1." "."html-webpack-plugin": "^ 4.3.0"."imagemin-webpack-plugin": 1 "" ^ 1.5.0 - beta.."mini-css-extract-plugin": "^ 1.3.3." "."npm": "^ 6.14.9"."optimize-css-assets-webpack-plugin": "^ 5.0.4"."purgecss-webpack-plugin": "^ 3.0.0"."style-loader": "^ 2.0.0." "."terser-webpack-plugin": "^ 4.0.0"."uglifyjs-webpack-plugin": "^ 2.2.0." "."url-loader": "^ 4.4.1"."webpack": "^ 4.44.2"."webpack-bundle-analyzer": "^ 4.2.0"."webpack-cli": "^" 3.3.12
    },
    "author": ""."license": "ISC"
}
Copy the code

reference

  • 18 popular Webpack plugins, there’s always something for you!

  • Webpack is a popular plugin


Welcome to the front-end birds to learn and communicate ~ 516913974