Webpack records - webpack 5 change records

Luma 2021-02-23 16:10:30
webpack records webpack change records


webpack.docschina.org/blog/2020-1…

introduction

2020 year 10 month ,webpack Released webpack 5.0.0. As the core competence of front-end engineering ,webpack The team considers the learning costs of the developers , It didn't make a big API upgrade (ღ( ´・ᴗ・)ღ), Compared with webpack4, Record and share some core upgrade points `


Node.js Polyfills No more introduction of

webpack 5 Start , Focus more on front end engineering build , No more auto fill Node Api shim , Improve web Building efficiency

webpack 4

import { crypto } from 'crypto';
console.log('node Module test ');
 Copy code 

these polyfill It's huge , Waste performance ,webpack It also gives a warning , We need other ways to optimize (polyfill.io)

webpack 5

import { crypto } from 'crypto';
console.log('node webpack5 Module test ');
 Copy code 

webpack 5 No longer import and compile failed , I hope you're working for these node api, To configure polyfill

If you use Node modular , We can turn it on with the following configuration :

// webpack.config.js
module.exports = {
mode: 'production',
...
resolve: {
fallback: {
// With crypto give an example , If you use some api, It can be compatible with 
"crypto": require.resolve("crypto-browserify"),
// Totally useless , No gasket is introduced , It can be turned off by the following configuration 
"crypto": false
}
}
}
 Copy code 

Support resource module compilation

webpack5 Start , The ability to compile various resource files is built in ,jpg/gif/txt/.. And other resource files are no longer needed adopt file-loader, url-loader And so on Loader Expanded and compiled .

Now? webpack Natural supports the following modules webpack The following module types are naturally supported `

  • ECMAScript modular
  • CommonJS modular
  • AMD modular
  • Assets
  • WebAssembly modular

before , We go through url-loader To optimize some small files ( < 1024 * 5 transformation base64)

Now for the rule configuration of common resource class , It can be done in the following ways :

// webpack.config.js
// Mode one 
module.exports = {
mode: 'production',
...
// Writing a 
module: {
generator: {
'asset': {},
'asset/inline': {},
'asset/resource': {},
'asset/source': {},
}
}
// Write two 
module: {
parser: {
'asset': {},
'asset/inline': {},
'asset/resource': {},
'asset/source': {},
}
}
// Write three 
module: {
rules: [
{
test: /\.jpg$/,
type: 'asset/resource',
parser: {},
},
{
test: /\.png$/,
type: 'asset/inline',
parser: {},
},
{
test: /\.txt$/,
type: 'asset/source',
parser: {},
}
]
}
}
 Copy code 

webpack 5 The corresponding mode of internal modules is as follows asset/inline => url-loader, asset/source => raw-loader, asset/resource => file-loader.

More detailed rules can Click here

Persistent compilation cache mechanism update

webpack 5 in , New cache policy , Through the use of caching mechanism , Can greatly improve our development 、 Build speed of compilation .

webpack 4

webpack < 5 in , We usually use them babel Plug in configuration or manifest.json File index to optimize build speed

webpack 5

Add test code :


// webpack.config.js
module.exports = {
mode: "production",
...
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: [
{
loader: "babel-loader",
options: {
presets: [
"@babel/preset-react"
]
}
}
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html'
}),
],
...
}
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app.jsx';
ReactDOM.render(<App />, document.getElementById('root'));
//app.jsx
import React from 'react';
import { fnA1 } from './moduleA';
class App extends React.Component {
componentDidMount() {
fnA1();
}
render() {
return <div>hello react</div>;
}
}
export default App;
 Copy code 
webpack --config webpack.config.js
 Copy code 

The output of the two builds is as follows :

for the first time

The second time

The two build times are close to 3000ms, Next Turn on webpack5 Long cache mechanism

// webpack.config.js
module.exports = {
mode: "production",
...
cache: {
type: "fileSystem"
}
...
}
 Copy code 

Second build , You can see the speed is up 6 times .

Can be in node_modules/.cache/webpack Cache file found in , It can be done by cacheDirectory Configure to modify the cache path .

In practice ,webpack Provided in the fileSystem | memory Two ways , memory It will cache the build products to the system memory to improve the build speed , This model can only be used in development Use... In mode .

By default ,webpack 5 In the construction of production mode , Will use file + Content Conduct hash Value calculation , In development mode, the timestamp is used for caching , With the long-term cache algorithm mechanism ,webpack5 It's also updated moduleIds 、chunkIds The generation mechanism of 【 Look below 】.

Optimization And moduleIds 、chunkIds Changes

【Tip】 module and chunk It can be simply understood as a file before compilation , One is the product of compilation , One file corresponds to one module, One code block corresponds to one chunk, Different chunk Mutual reference . Usually , The script that runs on the browser is also called bundle.

webpack 5 Before , The asynchronous module outputs in the form of digital increment , In this way, the caching mechanism will fail in some cases

webpack4

webpack4 Add the code

// demo/index.js 
import { comm1, comm2 } from './d';
(async () => {
await import('./a');
await import('./b');
await import('./c');
})()
console.log(comm1, comm2);
// webpack.config.js
module.exports = {
mode: "production",
...
optimization: {
splitChunks: {
chunks: 'all',
minSize: 500,
minChunks: 1,
cacheGroups: {
defaultVendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
reuseExistingChunk: true,
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true,
},
},
}
},
}
 Copy code 

The compiled output is as follows :

webpack5

The same document , stay webpack 5 in , It will be output as a short number id.

webpack 5, Will be in production In mode , Default on chunkIds: "deterministic" Pattern , Cache the contents of files at the content level .

More powerful tree-shaking

webpack Another important optimization algorithm is tree-shaking, webpack 5 comparison webpack4, Yes tree-shaking The algorithm is further enhanced : Supporting nested modules tree-shaking And Internal modules tree-shaking

webpack 4

Add the code

// a.js
function a () {
console.log('a')
}
function b () {
console.log('b')
}
export default {
a, b
}
// index.js
import a from './a'
console.log(a.a());
console.log('hello world');
 Copy code 

webpack 4 Build output :

webpack 4 lookup a There is... In the module a.a() The introduction of , So will a Module .

webpack 5

The same introduction and use ,webpack 5 More intelligent , Will optimize the multi-layer dependency module :

You can find ,b It's been eliminated correctly .

Module Federation

In addition to the above key configuration or optimization changes ,webpack For remote asynchronous loading bundle Added Module Federation Loading mechanism , It allows multiple webpack Build products to work together . Allows you to import... From a specified remote build , And use remote... With minimal restrictions js bundle.

This loading mechanism , Great for Microfront How to load , Because the mechanism of the micro front end itself is to load a segment across domains js Script to insert the third party module view .

The federated module test will be updated later demo.

summary


overall ,webpack 5 In order to reduce the learning cost of developers , Optimize the core algorithm and module optimization mechanism as small as possible , Give Way webpack More powerful , It does not increase the cost of our study , This makes our old projects move and upgrade webpack5 It's easier . The key update points can be summarized as follows :

  • Persistent caching to improve build performance .
  • More powerful Tree Shaking Algorithm
  • The increase in compiling power , Pay more attention to web The ability to build
  • Better content level hash The algorithm improves the long-term cache
  • Solutions for modern complex business
版权声明
本文为[Luma]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210223155148588Y.html

  1. RxHttp - 轻量级、可扩展、易使用、完美兼容MVVM、MVC架构的网络封装类库
  2. Rxhttp - lightweight, extensible, easy to use, perfectly compatible with MVVM, MVC architecture network encapsulation class library
  3. Rxhttp - lightweight, extensible, easy to use, perfectly compatible with MVVM, MVC architecture network encapsulation class library
  4. 前端面试常考题:JS垃圾回收机制
  5. Frequently asked questions in front end interview: JS garbage collection mechanism
  6. Rxhttp - lightweight, extensible, easy to use, perfectly compatible with MVVM, MVC architecture network encapsulation class library
  7. Java之HTTP网络编程(一):TCP/SSL网页下载
  8. HTTP network programming in Java (1): TCP / SSL web page download
  9. Java之HTTP网络编程(一):TCP/SSL网页下载
  10. HTTP network programming in Java (1): TCP / SSL web page download
  11. 使用vite搭建vue项目
  12. 在组件中展示pdf文件:vue-pdf (由于未找到方法滑动加载下一页,只能点击加载下一页pdf文件)
  13. 在 vue 中通过 express 连接数据库
  14. Using vite to build Vue project
  15. Display PDF file in component: Vue pdf
  16. Connecting database through express in Vue
  17. 2021届秋招哈啰出行前端面经(一面)
  18. vue使用sdk进行七牛云上传
  19. Javascript性能优化【内联缓存】 V8引擎特性
  20. Small true wireless smart headset evaluation: put intelligence into the ear
  21. The front end experience of the 2021 autumn recruitment
  22. Vue uses SDK to upload Qi Niu cloud
  23. 深入理解 Web 协议 (三):HTTP 2
  24. dhtmlxGantt如何重新排序任务
  25. JavaScript performance optimization [inline cache] V8 engine features
  26. 深入理解 Web 协议 (三):HTTP 2
  27. Deep understanding of Web protocol (3): http 2
  28. 深入理解 Web 协议 (三):HTTP 2
  29. How dhtmlxgantt reorders tasks
  30. 深入理解 Web 协议 (三):HTTP 2
  31. JavaScriptBOM操作
  32. JavaScriptBOM操作
  33. Deep understanding of Web protocol (3): http 2
  34. Deep understanding of Web protocol (3): http 2
  35. dhtmlxGantt甘特图重新排序任视频教程
  36. vue实现七牛云上传图片功能
  37. vue.js环境配置步骤及npm run dev报错解决方案
  38. Deep understanding of Web protocol (3): http 2
  39. JavaScript BOM operation
  40. JavaScript BOM operation
  41. Dhtmlxgantt reordering video tutorial
  42. Vue to achieve seven cattle cloud upload image function
  43. vue.js Environment configuration steps and NPM run dev error reporting solution
  44. 什么是HTTPS以及如何实施HTTPS?
  45. vue使用sdk进行七牛上传
  46. JavaScript 邮箱验证 - 正则验证
  47. Codeless development platform cloud watch sets off a "new revolution" in enterprise Digitalization
  48. Codeless development of cloud watch for enterprise digital solution
  49. What is HTTPS and how to implement it?
  50. Vue uses SDK to upload seven cows
  51. JavaScript mailbox verification - regular verification
  52. JavaScriptBOM操作
  53. JavaScript BOM operation
  54. How to create a new NPM package and publish it to the NPM community
  55. vue --tinymce 解决上传图片的方法
  56. Vue development
  57. A simple solution for vite to batch introduce SVG symbol
  58. Building 3D rendering engine from scratch with JS (2)
  59. Vue -- tinymece solution to upload pictures
  60. Common configuration of nginx