<>webpack5 use
<>1. Install dependency package
* Create a folder
* npm init generate package.json folder Then install the dependency cnpm webpack webpack-cli
html-webpack-plugin webpack-dev-server cross-env -D
* New one webpack.config.js File write configuration
* newly build src/inde.js file
* New template file src/index.html
* packjson command "scripts": { "build": "webpack", // For direct packing "start": "webpack
serve", // Start the server It can be used for development },
* Well configured entry and output You can use the basic version of module.exports = { mode: 'development',
// Configuration mode devtool: 'source-map', // Debugging tools context: process.cwd(), //
node The current directory of the process in which the command runs This is the root directory of the project entry: { main: './src/index.js' }, output: { path:
path.resolve(__dirname, 'dist'), filename: '[name].js' }, module: { }, plugins:
[ new HtmlWebpackPlugin({ template: './src/index.html', minify: { // compress html
collapseWhitespace: true, // Compress blanks removeComments: true // Remove comments } }), ] };
<>2. Install plug-ins
<>2.1 Log beautification installation
* friendly-errors-webpack-plugin Can identify a category of webpack error , And clean it up , Aggregation and prioritization , To provide a better developer experience
cnpm i friendly-errors-webpack-plugin node-notifier -D
* Using the error prompt plug-in const FriendlyErrorsWebpackPlugin = require(
'friendly-errors-webpack-plugin'); const notifier = require('node-notifier');
const icon = path.join(__dirname, 'icon.jpg'); plugins: [ ... + new
FriendlyErrorsWebpackPlugin({ + onErrors: (severity, errors) => { + let error =
errors[0]; + notifier.notify({ + title: 'webpack Compilation failed ', + message: severity +
':' + error.name, + subtitle: error.file || '', + icon + }); + } + }), ]
<>2.2 velocity analysis
* speed-measure-webpack5-plugin Analyze the packing speed cnpm i speed-measure-webpack5-plugin
-D const SpeedMeasureWebpack5Plugin = require('speed-measure-webpack5-plugin');
const smw = new SpeedMeasureWebpack5Plugin(); module.exports = smw.wrap({ //
configuration file mode: 'development', // Configuration mode devtool: 'source-map', // Debugging tools context:
process.cwd(), // node The current directory of the process in which the command runs This is the root directory of the project entry: { main: './src/index.js' },
output: { path: path.resolve(__dirname, 'dist'), filename: '[name].js' }, module
: { }, plugins: [ ] })
time analysis
<>2.3 File volume monitoring
* webpack-bundle-analyzer It's a webpack plug-in unit , Need to cooperate webpack and webpack-cli Use together ,
Production code analysis report ,
* You can analyze the size of the packaged file , Dependency , How about the compression size .
<>2.3.1 install
cnpm i webpack-bundle-analyzer -D const { BundleAnalyzerPlugin } = require(
'webpack-bundle-analyzer'); plugins: [ ... + new BundleAnalyzerPlugin({ +
analyzerMode: 'disabled', // Do not start displaying packaged reports HTTP The server It can also be activated We can see the effect directly + generateStatsFile
: true // To generate stats.json file + }), ]
command :
"build": "webpack", // Will generate stats.json file // Next time you want to see the results of the analysis, do it analyzer Start the service "analyzer":
"webpack-bundle-analyzer --port 8888 ./dist/stats.json"
<>3. Compile time optimization
* Reduce files to process
* Narrow your search
<>3.1 Narrow your search
<>3.1.1 extensions
* appoint extensions You don't have to require or import Add a file extension when you need it
* When searching, we will try to add extension names in turn for matching resolve:{ extensions: ['.js', '.jsx','.json'] }
<>3.1.2 alias
* Configure aliases faster webpack Find the speed of the module
* Whenever introduced bootstrap When you use the module , It will be introduced directly bootstrap You don't need to node_modules Search in the folder according to the search rules of the module install
cnpm i bootstrap css-loader style-loader -S const bootstrap = path.resolve(
__dirname, 'node_modules/bootstrap/dist/css/bootstrap.css' ); alias: {
bootstrap // Find alias },
<>3.2 cache
* Using caching
* An attempt is made to read the cache when the component is rebuilt , So as to improve the packing speed
* Cache location node_modules/.cache/babel-loader module: { rules: [ { test:
/\.js$/, include: path.resolve(__dirname, 'src'), exclude: /node_modules/, //
No analysis use: [ // Turn on multi thread pool It takes time to open thread and communicate with thread { loader: 'thread-loader', options: {
workers: 3 } }, { loader: 'babel-loader', options: { cacheDirectory: true //
automatic babel cache } } ] }, ] }
<>3.3 cache-loader
* In some areas with high performance overhead loader Add this before loader, The results can be cached on disk
* Save by default in node_modules/.cache/cache-loader Under the directory cnpm i cache-loader -D { test:
/\.css$/, use: [ 'cache-loader', 'css-loader' ] }
<>3.4 hard-source-webpack-plugin
* hardSourceWebpackPlugin Provides an intermediate cache for the module , The default path to store the cache is
node_modules/.cache/hard-source
* The first build didn't change much , The second build time can be reduced approximately 80%
* webpack5 The module cache has been built in , You no longer need to use this plug-in
<>4. Compiler volume optimization
<>4.1 compress js,css,HTML And pictures
* optimize-css-assets-webpack-plugin It's an optimization and compression css Plug in for resources
* terser-webpack-plugin It's an optimization and compression js Plug in for resources
* image-webpack-loader It can help us compress and optimize the image
<>4.1.2 install
cnpm i terser-webpack-plugin optimize-css-assets-webpack-plugin
image-webpack-loader -D const OptimizeCssAssetsWebpackPlugin = require(
'optimize-css-assets-webpack-plugin'); const TerserWebpackPlugin = require(
'terser-webpack-plugin'); { // js compress optimization: { minimize: true, // Start minimizing
minimizer: [new TerserWebpackPlugin()] }, module: { rules: [ { test:
/\.(jpg|png|gif|bmp)$/, 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.9],
speed: 4 }, gifsicle: { interlaced: false }, // the webp option will enable WEBP
webp: { quality: 75 } } } ] }, ] }, plugins: [ ... + new
OptimizeCssAssetsWebpackPlugin() // compress css ] }
<>4.2 Remove useless css
* purgecss-webpack-plugin mini-css-extract-plugin Separate extraction css And remove the unused css
<>4.2.1 install
cnpm i purgecss-webpack-plugin mini-css-extract-plugin -D const
PurgecssWebpackPlugin= require('purgecss-webpack-plugin'); const
MiniCssExtractPlugin= require('mini-css-extract-plugin'); const glob = require(
'glob'); const PATHS = { src: path.resolve(__dirname, 'src') }; module: { rules:
[ { test: /\.css$/, use: [ 'cache-loader', 'log-loader', + MiniCssExtractPlugin.
loader, // stay css loader Pre introduction 'css-loader' ] } ], }, plugins: [ // Extracted css file name + new
MiniCssExtractPlugin({ + filename: '[name].css' + }), + // /**/* ** Match any field
Include path separator * Match any character Does not contain a path separator ,, // Get rid of useless css new PurgecssWebpackPlugin({ paths: glob.
sync(`${PATHS.src}/**/*`, { nodir: true }) }), + ]
<>5. environment
<>4.1 mode Default value for
* webpack Of mode default production
* webpack serve Of mode Default to development
* It can be passed in the module process.env.NODE_ENV Gets the current environment variable , Can't be in webpack Get this variable from the configuration file
<>4.2 modify
* Command line plus –mode=production Can be assigned You can override the configuration file priority default mode <config < --mode to configure
<>4.3 DefinePlugin modify
* Set global variables All modules can read the value of the variable
* It can be used in any module process.env.NODE_ENV Gets the current environment variable
* But not in the node environment (webpack In the configuration file ) Get the current environment variable under // Define global variables modify process.env.NODE_ENV
plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(
'production'), ENV: JSON.stringify('ENV') }) ]
* The module code can read the variables defined above
<>4.4 cross-env set up
npm i cross-env -D
command line
"build1": "cross-env NODE_ENV=development webpack",
The value can be read in the configuration file cross-env Set the value to add by pressing to process.env In the object
<>4.5 .env Document modification
New root directory .env file
// .env Document content NODE_ENV=development ENV=TEST cnpm i dotenv -D // Can read .env file ,
Get the value inside Set to process.env inside require('dotenv').config();
<> Summary
webpack5 and webpack4 The configuration is basically the same , There won't be much difference in use , dll It has been removed , use
hard-source-webpack-plugin Substitute, etc .
* Improve performance through persistent caching
* Better persistent caching algorithm and default behavior
* Through optimization Tree Shaking And code generation Bundle volume
* increase Web Platform compatibility
* Before clearing, in order to achieve Webpack4 There is no irrationality caused by incompatible changes state
* Try to introduce major changes now to prepare for future functionality , So that we can use it as long as possible Webpack 5
* automatic Polyfills some Node modular ( for example crypto) It will undoubtedly increase the packing volume , stay Webpack5 The automatic behavior is then removed
attach :
Complete configuration of test process
/* * @description: * @author: steve.deng * @Date: 2020-12-19 06:51:55 *
@LastEditors: steve.deng * @LastEditTime: 2020-12-22 14:38:50 */ const path =
require('path'); const FriendlyErrorsWebpackPlugin = require(
'friendly-errors-webpack-plugin'); const notifier = require('node-notifier');
const icon = path.join(__dirname, 'icon.jpg'); const SpeedMeasureWebpack5Plugin
= require('speed-measure-webpack5-plugin'); const { BundleAnalyzerPlugin } =
require('webpack-bundle-analyzer'); const HtmlWebpackPlugin = require(
'html-webpack-plugin'); const smw = new SpeedMeasureWebpack5Plugin(); const
selfLoadersPath= path.resolve(__dirname, 'loader'); const webpack = require(
'webpack'); const TerserWebpackPlugin = require('terser-webpack-plugin'); const
OptimizeCssAssetsWebpackPlugin= require('optimize-css-assets-webpack-plugin');
const ImageWebpackLoader = require('image-webpack-loader'); const
PurgecssWebpackPlugin= require('purgecss-webpack-plugin'); // because css and js Loading can be done in parallel
So we can extract it through this plug-in css It is a separate file Then get rid of the useless css Compress const MiniCssExtractPlugin = require(
'mini-css-extract-plugin'); const glob = require('glob'); const { DefinePlugin }
= require('webpack'); const PATHS = { src: path.resolve(__dirname, 'src') };
const bootstrap = path.resolve( __dirname,
'node_modules/bootstrap/dist/css/bootstrap.css' ); // Can read .env file , Get the value inside
Set to process.env.NODE_ENV inside require('dotenv').config(); console.log('.env
process.env.NODE_ENV', process.env.NODE_ENV); console.log('.env ENV', process.
env.ENV); // Default value undefined Unable to get in configuration file It can be obtained in the module code console.log(
'process.env.NODE_ENV', process.env.NODE_ENV); module.exports = smw.wrap({ //
mode: 'development', // Configuration mode devtool: 'source-map', // Debugging tools context: process.
cwd(), // node The current directory of the process in which the command runs This is the root directory of the project entry: { main: './src/index.js' }, output:
{ path: path.resolve(__dirname, 'dist'), filename: '[name].js' }, // js compress
optimization: { minimize: true, // Start minimizing minimizer: [new TerserWebpackPlugin()]
}, resolve: { extensions: ['.js', '.jsx', '.json'], // Specify the extension alias: { bootstrap
// Find alias }, modules: ['node_modules'], // Specify the lookup directory mainFields: ['browser', 'module'
, 'main'], // from package.json Which field in find the entry file mainFiles: ['index'] //
If you can't find it mainFields In my words The index file will be found index.js }, resolveLoader: { modules: [selfLoadersPath,
'node_modules'] // selfLoadersPath custom loader analysis }, externals: { jquery: 'jQuery'
}, module: { rules: [ { test: /\.js$/, include: path.resolve(__dirname, 'src'),
exclude: /node_modules/, // No analysis use: [ // Turn on multi thread pool It takes time to open thread and communicate with thread { loader:
'thread-loader', options: { workers: 3 } }, { loader: 'babel-loader', options: {
cacheDirectory: true // automatic babel cache } } ] }, { test: /\.(jpg|png|gif|bmp)$/, use:
[ { loader: 'image-webpack-loader', options: { mozjpeg: { progressive: true },
// optipng.enabled: false will disable optipng optipng: { enabled: false },
pngquant: { quality: [0.65, 0.9], speed: 4 }, gifsicle: { interlaced: false },
// the webp option will enable WEBP webp: { quality: 75 } } } ] }, { test:
/\.css$/, use: [ 'cache-loader', 'log-loader', MiniCssExtractPlugin.loader,
'css-loader' ] } ] }, plugins: [ new HtmlWebpackPlugin({ template:
'./src/index.html', minify: { // compress html collapseWhitespace: true, // Compress blanks
removeComments: true // Remove comments } }), new MiniCssExtractPlugin({ filename:
'[name].css' }), // /**/* ** Match any field Include path separator * Match any character Does not contain a path separator ,, // Get rid of useless css new
PurgecssWebpackPlugin({ paths: glob.sync(`${PATHS.src}/**/*`, { nodir: true }) }
), new FriendlyErrorsWebpackPlugin({ onErrors: (severity, errors) => { let error
= errors[0]; notifier.notify({ title: 'webpack Compilation failed ', message: severity + ':' +
error.name, subtitle: error.file || '', icon }); } }), new BundleAnalyzerPlugin(
{ analyzerMode: 'disabled', // Do not start displaying packaged reports HTTP The server generateStatsFile: true //
To generate stats.json file }), // Ignore module packaging For example, language pack new webpack.IgnorePlugin({ resourceRegExp:
/^\.\/locale$/, // Resource regularization contextRegExp: /moment$/ // context , Catalog regularity }), // Define global variables new
webpack.DefinePlugin({ // Defines the global variables used in compilation In the browser runtime, it is the value // 'process.env.NODE_ENV':
JSON.stringify('production'), 'process.env.NODE_ENV': JSON.stringify(process.env
.NODE_ENV), ENV: JSON.stringify('ENV') }), new OptimizeCssAssetsWebpackPlugin()
// compress css ] });
Technology