Pull out the common code

Learn how to remove common code from Webpack

The code to be extracted

1. Public modules

Public module code does not need to be repeatedly packaged, separate into a [public module] file, can be directly referenced, such as some utils code

2. Third-party module code

The code of the third party module will not change easily. There is no need to repackage the business code after it changes, separate it into a file of [third party module], and then reference it like loadsh

implementation

In the production environment, modify the configuration of the build file

optimization: {
    splitChunks: {// all Splits both synchronous and asynchronous codes
        // Async does code splitting only for asynchronous code
        // initial splits only synchronized code
        Inport loadsh from 'loadsh'
        // Asynchronous code import('loadsh')
        
        chunks: 'all'.cacheGroups: {
            // Third party module
            vendor: {
                name: 'vendor'.// For example, loadsh can be classified as either a public module or a third module. If the third module has a higher priority than the public module, it can be detected first
                priority: 1.// Check whether it comes from node_modules
                test: /node_modules/.// To see the effect of code splitting, set the value to a minimum
                minsize: 0.minChunks: 1
            },
            // Public module
            common: {
                // Name of each group
                name: 'common'.// Priority, the higher the priority, the earlier the detection processing,
                priority: 0.// In real development, it can be written as 5*1024, which is 5KB
                minsize: 0.// The detection module is referenced several times
                // For third-party modules, reference once should be packaged separately
                // For public modules, more than two references should be packaged separately
                minChunks: 2}}}}Copy the code