First, split the scene
Why code split?
- 1. In common scenarios
After the main.js package generated 2m code is published, the user visits the page several times, and the content of 2m is reloaded each time
- 2. Code segmentation
Js is split into main.js(1m size) and A.js (1m size). A.js is the introduction of a common JS library. When the page business logic changes, just reload main.js and A.js will cache the page
Code segmentation in Webpack
- Methods a
Sync code: Simply configure the optimization parameter in webpack.common.js
module.exports = {
...
optimization: {
splitChunks: {
chunks: 'all'
}
}
...
}
Copy the code
- Way 2
Asynchronous code (import): code is automatically split in SRC /index.js without any configuration
function getComponent() {
return import('lodash').then(({ default: _ }) => {
var element = document.createElement('div');
element.innerHTML = _.join(['Dell', 'Lee'], '-');
return element;
})
}
getComponent().then(element => {
document.body.appendChild(element);
})
Copy the code