In projects created with Vue CLI 3, Webpack is already built-in and configured, including configurations for code splitting.
In Vue CLI 3 and higher versions, by default, it uses a code splitting strategy based on Webpack to improve application loading speed and efficiency. This is achieved through the splitChunks configuration, which internally configures the Webpack optimization section.
Step 1: Understanding Vue CLI Project Structure
In Vue CLI 3-generated projects, Webpack's configuration is encapsulated and typically not directly visible in project files. However, you can extend or modify the default Webpack configuration through the vue.config.js file.
Step 2: Modifying vue.config.js
To customize code splitting, you can modify or create a vue.config.js file in the project's root directory. Below is a basic example of how to configure this file for custom code splitting:
javascriptmodule.exports = { chainWebpack: config => { config.optimization.splitChunks({ chunks: 'all', maxInitialRequests: 5, // Maximum number of parallel requests during initial load minSize: 30000, // Minimum size required to form a new chunk automaticNameDelimiter: '.', // Delimiter used when generating names cacheGroups: { vendor: { name: 'vendor', test: /[\/]node_modules[\/]/, priority: -10, chunks: 'initial' }, common: { name: 'common', minChunks: 2, priority: -20, chunks: 'initial', reuseExistingChunk: true } } }); } }
Step 3: Understanding splitChunks Options
- chunks: Specifies which chunks will be selected for optimization. When set to
'all', it means chunks can share blocks even in asynchronous and non-asynchronous chunks. - maxInitialRequests: Maximum number of parallel requests allowed for entry points.
- minSize: Minimum size required to form a new chunk.
- cacheGroups: Configures cache groups for code splitting. You can define multiple cache groups for finer control.
Step 4: Testing and Verification
After modifying the configuration, run the project and use the browser's developer tools to inspect network requests, verifying that JS files are split into different chunks as expected. You can also use the Webpack Bundle Analyzer plugin to visually inspect the size and composition of output files.
Conclusion
By doing this, you can flexibly utilize Webpack's performance features in Vue CLI 3 projects to optimize frontend resource loading. This is particularly important for large applications, as it reduces initial load time and improves user experience.