Why do you need a build tool?

  • Converting ES6 syntax (not supported in earlier browsers)
  • CSS prefix completion automatically, SCSS/LESS preprocessor compilation
  • Js/CSS code compression and obfuscation
  • Image file compression

What are the build tools?

  • grunt
  • gulp
  • fis3
  • rollup
  • parcel
  • webpack
  • vite

Related concepts and configuration reference

The configuration file

The default webpack configuration file is webpack.config.js

Configuration files can be specified via webpack –config

Module.exports = {entry: './ SRC /index.js', // exports = {entry: './ SRC /index.js', // exports = {entry: './ SRC /index.js', // exports = {entry: './ SRC /index.js', // exports = {entry: './ SRC /index.js', // exports = {entry: '. 'production', // dev module: {rules: [// loader config test: /\.txt$/, use: 'raw-loader']}, plugins: HtmlwebpackPlugin({template: './ SRC /index.html'})]}Copy the code

Entry: Packing Entry

Single file entry

module.exports = {
    entry: './path/to/my/entry/file.js',
}
Copy the code

Multi-file entry (multi-page application)

module.exports = {
    entry: {
        app: './src/app.js',
        adminApp: './src/adminApp.js',
    },
}
Copy the code

Output: the output

Output tells WebPack how to output the compiled file to disk

Single file entry

Module. Exports = {entry: '/ path/to/my/entry/file. The js' output: {filename:' bundle. Js' path: __dirname + '/ dist'}};Copy the code

Multifile entry

module.exports = { entry: { app: './src/app.js', search: './src/search.js' }, output: { filename: '[name]_[chunkhash:8].js', // make sure file name is unique with placeholder path: __dirname + '/dist'}}; // Write to disk:./dist/app.js,./dist/search.jsCopy the code

Loaders: indicates the loader

Webpack supports only JS and JSON file types out of the box, Loaders supports other file types and converts them into valid modules that can be added to dependency diagrams.

What are the common Loaders?

The name of the describe
babel-loader Convert ES6, ES7 advanced JS new feature syntax
css-loader Supports loading and parsing of. CSS files
less-loader Parse less files into CSS
file-loader Package pictures and fonts
raw-loader Import the file as a string
thread-loader Multi-process packaging OF JS and CSS

The use of the loader

module.exports = {
    module: {
        rules: [
            { 
                test: /\.css$/, 
                use: [
                    { 
                        loader: 'style-loader' 
                    },
                    {
                        loader: 'css-loader',
                        options: {
                            modules: true
                        }
                    },
                    { 
                        loader: 'sass-loader'
                    }
                ]
            },
            { 
                test: /\.ts$/, 
                use: 'ts-loader'
            },
        ],
    },
};

Copy the code

Plugins: Plugins

Some loaders can’t handle it. Plugins are used for bundle optimization, resource management, and environment variable injection, and are used throughout the build process

What are common Plugins?

The name of the describe
CommonsChunkPlugin Chunks of the same module code are extracted as common JS
CleanWebpackPlugin Directory cleanup plug-in
ExtraTextWebpackPlugin Extract CSS from bunlde files into a separate CSS file
CopyWebpackPlugin Copy files or folders to the output directory of the build
HtmlWebpackPlugin Create an HTML file to load the bundle file for the output
UglifyjsWebpackPlugin Compression js

The use of the Plugins

const HtmlWebpackPlugin = require('html-webpack-plugin'); // install const webpack = require('webpack') via NPM; // Access the built-in plugin const path = require('path'); module.exports = { entry: './path/to/my/entry/file.js', output: { filename: 'my-first-webpack.bundle.js', path: path.resolve(__dirname, 'dist'), }, module: { rules: [ { test: /\.(js|jsx)$/, use: 'babel-loader', }, ], }, plugins: [ new webpack.ProgressPlugin(), new HtmlWebpackPlugin( { template: './src/index.html' } ), ], };Copy the code

Mode: construction environment

Mode specifies whether the current build environment is: production, development, or None. Setting Mode can use the built-in webpack function, which defaults to production

options

Externals: external extension

Reduce packaging speed and public package size by introducing common library files via script tag external links

externals: {
	'vue': 'Vue',
	'element-ui': 'ELEMENT',
	'vue-router': 'VueRouter',
	'vuex': 'Vuex',
	'axios': 'axios'
},
Copy the code

Resolve: Resolves files

Resolve: {// Import files without extensions:['.js', '.json', '.vue'], // import alias: {'@images': path.resolve(__dirname, './assets/images'), '@style': path.resolve(__dirname, './assets/style'), '@src': path.resolve(__dirname, './src'), } }Copy the code

Target: The target of the packaged output

The default package output of v5 is self-executing functions with arrow functions, which is not compatible and needs to be set to

// WebPack will generate runtime code for the Web platform and only use ES5-related features. target: [ 'web', 'es5' ]Copy the code

Module hot update

Suitable for development environment, using webpack-dev-server

Note that webPack V5 requires an installation prior to 4.0, which removed contentBase

DevServer: {contentBase: path.join(__dirname, './dist'), host: 'localhost', port: '9000', open: true, True, // Start module hot update}Copy the code

File compression

HTML compression

HtmlWebpackPlugin simplifies the creation of HTML files

const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { plugins: [new HtmlWebpackPlugin({template: path.resolve(__dirname, 'SRC /index.html'), // ['main'], inject: true, minify: { html5: true, collapseWhitespace: true, preserveLineBreaks: false, minifyCSS: true, minifyJS: true, removeComments: false } }) ] };Copy the code

Js compression and encryption

The TerserPlugin uses Terser to compress JavaScript.

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

module.exports = {
    optimization: {
        minimize: true,
        minimizer: [
            new TerserPlugin()
        ],
    },
};
Copy the code

Js encryption plugin Webpack-Obfuscator

CSS compression

CssMinimizerWebpackPlugin plug-in cssnano optimization and compression using CSS.

Optimization: {minimizer: [new CssMinimizerPlugin({parallel: true, // Preset: ["advanced"], // cssnano https://cssnano.co/docs/optimisations/ } }), ], },Copy the code

Image compression

The image-webpack-loader plug-in is compressed

/ / resolution images {test: / \. (JPG | jpeg | PNG | | GIF SVG) $/ I type: 'asset/resource', / / v5 built-in module parse static resource generator: {filename: 'static/images/[contenthash][ext][query]'}, use: [// image compression {loader: 'image-webpack-loader', options: {mozjpeg: { progressive: true, }, // optipng.enabled: false will disable optipng optipng: { enabled: false, }, pngquant: {quality: [0.65, 0.90], speed: 4}, GIFsicle: {interlaced: false,}, // The webp option will enable webp webp: { quality: 75 } } } ] }Copy the code

The CSS automatically adds prefixes

PostCSS plugin Autoprefixer automatically fills CSS3 prefixes according to Can I Use rule (caniuse.com/)

Const autoprefixer = the require (' autoprefixer ') / / parsing SCSS {test: / \. (s (ac) ss | CSS) $/ I, use: [ MiniCssExtractPlugin.loader 'css-loader', 'sass-loader', { loader: Postcss-loader: postcss.config.js options: {postcssOptions: {postcssOptions: [autoprefixer]}}]}Copy the code

Add. Browserslistrc file to add browser rules

last 2 version
> 1%
ie > 8
Copy the code

Js public package separation

SplitChunks is configured to set segmentation rules

splitChunks: {
    cacheGroups: {
        commons: {
            test: /[\\/]node_modules[\\/]/,
            name: 'vendors',
            chunks: 'all',
        }
    }
}
Copy the code

The CSS file is removed

The MiniCssExtractPlugin extracts CSS into a separate file, creating a CSS file for each JS file that contains CSS.

const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
    plugins: [new MiniCssExtractPlugin()],
        module: {
        rules: [
            {
                test: /\.css$/i,
                use: [
                    MiniCssExtractPlugin.loader, 
                    "css-loader"
                ],
            },
        ],
    },
};

Copy the code

Dynamic load on demand

Js lazy loading, common.js require.ensure, es6 dynamic import (requires Babel plugin conversion)

{
    "plugins": ["@babel/plugin-syntax-dynamic-import"],
    ...
}
Copy the code

Tree shaking

A module may have multiple methods, and as long as one of them is used, the whole file will be sent to the bundle. Tree shaking is only putting used methods into the bundle, and unused methods will be erased during the Uglify phase.

Webpack is supported by default, production mode is enabled by default

Build optimized display

Stats is set to errors-only

Use the friendly-errors-webpack-plugin

plugins: [
  new FriendlyErrorsWebpackPlugin()
],
stats: 'errors-only'
Copy the code

Multi-process/multi-instance build

To use the official recommended Thread-loader, place this loader before other loaders. Loaders placed after this loader will run in a separate worker pool.

Please use this loader only for time-consuming operations!

module.exports = { module: { rules: [ { test: /\.js$/, include: path.resolve('src'), use: ["thread-loader", // Time-consuming loader (e.g. Babel-loader)],},],},};Copy the code

Build package dependency analysis

The webpack-bundle-Analyzer plug-in analyzes the volume