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