The Problem Solved by Code Splitting
Firstly, let's look at the problems with the traditional single chunk packaging mode:
- Can not import on demand
All the code is bundled into one chunk, which means that the code needed for page initialization and the code for the route components are all bundled together.
- Can not use network cache
Normally, the name of a chunk is generated based on the hash value of the file content. Therefore, every time the code is modified, the name of the chunk changes, which prevents the browser from using the local cache.
Code splitting is aimed at resolving these issues to enhance page load performance.
Vite's Default Chunk Splitting Strategy
Before version 2.9
- One chunk corresponds to one CSS file.
- Logic code will be packaged into one chunk.
- Third-party dependencies are packaged into one chunk.
After version 2.9
The changed place is that both the third-party packages and the business code are now in one chunk.
If you want to control the code splitting strategy with a finer granularity, you need to use the manualChunks configuration. The config is approximately as follows:
export default defineConfig({
build: {
rollupOptions: {
output: {
/**
* 1. Use in object form
* Package the lodash module into a chunk, named lodash
*/
manualChunks: {
lodash: ['lodash'],
},
/**
* 2. Use in function form
* Package all third-party packages into one chunk, named vendor
*/
manualChunks(id, { getModuleInfo, getModuleIds }) {
if (id.includes('node_modules')) {
return 'vendor';
}
},
},
},
},
});
Top comments (0)