This is the 9th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
(I) Initial experience of Webpackage 5
(2) core configuration of webpack5
(3) production configuration of webpack5
1. HTML code compression
Webpack is configured differently for development and production environments. By default, production code is compressed and does not need to be reconfigured. You only need to specify mode = “production”, however, if you want to compress HTML code, you need to add configuration
new HtmlWebpackPlugin({
template: './src/index.html'.minify: {
// Remove whitespace
collapseWhitespace: true.// Remove comments
removeComments: true}}),Copy the code
2. Production environment configuration summary
Mainly include:
- CSS, less and other file compatibility processing, has code compression
- HTML processing and compression
- Processing of images and other resources
- Configuration of esLint syntax
const { resolve } = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
process.env.NODE_ENV = 'production'
/ / reuse loader
const commonCssLoader = [
MiniCssExtractPlugin.loader,
'css-loader',
{
loader: 'postcss-loader'.options: {
postcssOptions: {
plugins: [
require('postcss-preset-env')()}}}]module.exports = {
entry: './src/js/index.js'.output: {
filename: 'js/bundle.js'.path: resolve(__dirname, 'build')},module: {
rules: [{test: /\.css$/,
use: [...commonCssLoader]
},
{
test: /\.less$/,
use: [...commonCssLoader, 'less-loader'] {},test: /\.js$/,
exclude: /node_modules/,
enforce: 'pre'.loader: 'eslint-loader'.options: {
fix: true}}, {test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'.options: {
presets: [
'@babel/preset-env',
{
useBuiltIns: 'usage'.corejs: { version: 3 },
targets: {
chrome: '60'.firefox: '50'}}]}}, {test: /\.(jpg|png|gif)/,
loader: 'url-loader'.options: {
limit: 8 * 1024.name: '[hash:10].[ext]'.outputPath: 'imgs'.esModule: false}}, {test: /\.html$/,
laoder: 'html-loader'
},
{
exclude: /\.(js|css|less|html|jpg|png|gif)/,
loader: 'file-loader'.options: {
outputPath: 'media'}}},plugins: [
new MiniCssExtractPlugin({
filename: 'css/bundle.css'
}),
new OptimizeCssAssetsWebpackPlugin(),
new HtmlWebpackPlugin({
template: './src/index.html'.minify: {
collapseWhitespace: true.removeComments: true}})].mode: 'production'
};
Copy the code
3. Webpack performance optimization
1. Development environment performance optimization
2. Optimized production environment performance
(1) Several aspects of development environment performance optimization:
-
Optimize packaging build speed
- Optimized code debuggingCopy the code
(2) Production environment performance optimization
- Optimize packaging build speed
- Optimize the performance of code execution
4. Replace the hot module
What it does: If a module changes, it will repackage the module instead of all modules, greatly improving the build speed. It is also very easy to enable HMR function, just configure hot: True in devServer
devServer: {
// Run the project directory
contentBase: resolve(__dirname, 'build'),
// Start compression
compress: true./ / the port number
port: 3000.// Automatically open the browser
open: true.// Enable HMR
hot : true,}Copy the code
Note:
1. Style files: The HMR function can be used because style-Laoder is implemented internally
2, JS files, the default can not use HMR function, need to modify js code, let it support HMR function, HMR function of JS processing, can only process non-entry JS files other files.
3. HTML files: HMR cannot be used by default, which will cause problems. HTML files cannot be hot updated
Solution: Modify the entry entry to import the HTML file
module.exports = {
entry: ['./src/index.js'.'./src/index.html'].output: {
filename: 'js/bundle.js'.path: resolve(__dirname, 'build')}},Copy the code
Of course, you can also configure a single block
if(module.hot) {
// Once module.hot is true, HMR is enabled,
module.hot.accept('./uitls.js'.function() {
// It listens for changes to the uitls.js file and does not repackage the rest of the build by default
print()
})
}
Copy the code
4, Webpack hot update principle?
Hot updates to Webpack are also known as Hot Module Replacement, or HMR.
This mechanism allows you to replace old modules with new ones without refreshing the browser.
1. Step 1: In Webpack’s Watch mode, when a file in the file system is modified, Webpack detects the file change, recompiles and packages the module according to the configuration file, and saves the packaged code in memory through simple JavaScript objects
2. Step 2: Interface interaction between Webpack-dev-server and Webpack, and in this step, mainly between Webpack-dev-middleware and Webpack, Webpack-dev-middleware calls the API exposed by Webpack to monitor code changes and tells Webpack to pack the code into memory.
3. Step 3: webpack-dev-server is a monitoring of file changes. This step is different from the first step and does not monitor code changes and re-pack. . When we are in the configuration file is configured with devServer watchContentBase to true, the Server will listen these configuration changes in static files in the folder, change will notify the browser after the live for the application to reload. Notice that this is browser refresh, and HMR are two different things.
4, the fourth step: this step is mainly through the establishment of a websocket long connection between the browser end and the Server end, the status information of each stage of Webpack compilation and packaging to inform the browser end, but also includes the information of the Server monitoring static file changes in the third step. The browser performs different operations based on these socket messages. Of course, the most important information passed by the server is the hash value of the new module, and the subsequent steps use this hash value to perform module hot replacement.
5. Step 5: The webpack-dev-server/client cannot request updated code and does not perform hot module operations, handing the work back to Webpack. The job of webpack/hot/dev-server is to decide whether to refresh the browser or hot update the module based on the information passed to it by webpack-dev-server/client and the configuration of dev-server. Of course, if you just refresh the browser, there are no steps
6. Step 6: HotModuleReplacement runtime is the centre of the client HMR, step on it receives hash value passed to his new module, it through JsonpMainTemplate. Runtime sends an Ajax request to the server end, The server returns a JSON package containing the hash values of all modules to be updated. Once the updated list is retrieved, the module requests the latest module code again through JSONP
7. Step 7: In this step, the HotModulePlugin will compare the old and new modules to determine whether to update them. After the decision is made, the dependency relationship between the modules is checked and the dependency references between the modules are updated as well
Step 8: When HMR fails, fall back to live Reload, which means a browser refresh to get the latest packaging code.
5. Webpack solves performance problems
To summarize the production configuration above:
1. Compress the code. Remove unnecessary code, comments, simplify code writing, and so on. Webpack UglifyJsPlugin and ParallelUglifyPlugin can be used to compress JS files, using CSSNano (CSS-loader? Minimize to compress CSS
2. CDN acceleration. During the build process, the referenced static resource path is changed to the corresponding path on the CDN. The resource path can be modified using the Webpack for the output parameter and the publicPath parameter of each loader
3. Tree Shaking dead code Remove pieces of code that never go anywhere. This can be done by appending the parameter optimize-minimize when starting the Webpack
4. Extract common code.
6, download the source code
Webpack5 learning source code