I. New projects

Build an initial VUE project with VUE-CLI3

With CLI3, many directory structures are missing, and the configuration is in vue.config.js, so in the root directory, create a vue.config.js

module.exports = {}
Copy the code

Second, formal optimization

1. Set productionSourceMap to false

Module. exports = vue.config.js

module.exports = {
    productionSourceMap: false
}
Copy the code

2, picture compression

After vue is packed normally, some image files are very large, which makes the packing volume very large. Image-webpack-loader plug-in can compress large images to reduce the packing volume

CNPM install image-webpack-loader –save-dev

Module. exports = vue.config.js

module.exports = {
    productionSourceMap: falseChainWebpack: config = > {/ / = = = = = = = = = = = = compressed images start = = = = = = = = = = = = config. The module. The rule ('images')
            .use('image-webpack-loader')
            .loader('image-webpack-loader')
            .options({ bypassOnDebug: trueEnd () // ============ end============}}Copy the code

3. CDN Configuration (Optional)

(1) Write at the top of vue.config.js:

// Whether it is a production environment const isProduction = process.env.node_env! = ='development'// Whether the local environment requires CDN const devNeedCdn =false// CDN link const CDN = {// CDN: externals: {vue:'Vue',
        vuex: 'Vuex'.'vue-router': 'VueRouter'}, // CDN CSS link CSS: [], // CDN js link js: ['https://cdn.staticfile.org/vue/2.6.10/vue.min.js'.'https://cdn.staticfile.org/vuex/3.0.1/vuex.min.js'.'https://cdn.staticfile.org/vue-router/3.0.3/vue-router.min.js']} (2) in vue. Config. Js. The module exports chainWebpack writes: / / = = = = = = = = = = = = injection CDN start = = = = = = = = = = = = config. The plugin ('html'Tap (args => {// Inject a CDN only when it is required in the production environment or locallyif (isProduction || devNeedCdn) args[0].cdn = cdn
    returnArgs}) // ============ insert CDN start============ (3) exports configureWebpack to vue.config.js module. Exports configureWebpack: Config => {// If CDN is used, related resources should be ignored during constructionif(isProduction | | devNeedCdn) config. Externals. = the CDN externals} (4) the current configuration of vue. Config. If js / / for the production environment const isProduction = process.env.NODE_ENV ! = ='development'// Whether the local environment requires CDN const devNeedCdn =false// CDN link const CDN = {// CDN: externals: {vue:'Vue',
        vuex: 'Vuex'.'vue-router': 'VueRouter'}, // CDN CSS link CSS: [], // CDN js link js: ['https://cdn.staticfile.org/vue/2.6.10/vue.min.js'.'https://cdn.staticfile.org/vuex/3.0.1/vuex.min.js'.'https://cdn.staticfile.org/vue-router/3.0.3/vue-router.min.js'
    ]
}

module.exports = {
    productionSourceMap: falseChainWebpack: config = > {/ / = = = = = = = = = = = = compressed images start = = = = = = = = = = = = config. The module. The rule ('images')
            .use('image-webpack-loader')
            .loader('image-webpack-loader')
            .options({ bypassOnDebug: true}). The end () / / = = = = = = = = = = = = compressed images end = = = = = = = = = = = = / / = = = = = = = = = = = = injection CDN start = = = = = = = = = = = = config. The plugin ('html'Tap (args => {// Inject a CDN only when it is required in the production environment or locallyif (isProduction || devNeedCdn) args[0].cdn = cdn
            returnThe args}) / / = = = = = = = = = = = = injection CDN start = = = = = = = = = = = =}, configureWebpack: config = > {/ / CDN way introduced, then the build time to ignore the related resourcesif (isProduction || devNeedCdn) config.externals = cdn.externals
    }
}
Copy the code

(5) Write to public index.html

<! DOCTYPE html> <html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
        <link rel="icon" href="<%= BASE_URL %>favicon.ico"/ > <! -- CSS files using CDN --> <%for (var i in htmlWebpackPlugin.options.cdn &&
        htmlWebpackPlugin.options.cdn.css) { %>
        <link
            href="<%= htmlWebpackPlugin.options.cdn.css[i] %>"
            rel="stylesheet"/> <%} %> <! -- CSS file using CDN --> <title>cli3_base</title> </head> <body> <noscript> <strong >We're sorry but cli3_base doesn't work properly without
                JavaScript enabled. Please enable it to continue.</strong
            >
        </noscript>
        <div id="app"></div> <! -- JS file using CDN --> <%for (var i in htmlWebpackPlugin.options.cdn &&
        htmlWebpackPlugin.options.cdn.js) { %>
        <script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script> <% } %> <! -- use CDN JS file --> <! -- built files will be auto injected --> </body> </html>Copy the code

(6) Restart the NPM Run Serve project

(7) Change it in SRC /router.js

will

Vue.use(Router)
Copy the code

Instead of

if(! window.VueRouter) Vue.use(Router)Copy the code

(8) Restart NPM Run serve. The current configuration is the development environment, which cannot be seen in the Network JS of the browser. If you want to view it, please view it in vue.config.js

// Whether the local environment requires CDN const devNeedCdn =false
Copy the code

Instead of

// Whether the local environment requires CDN const devNeedCdn =true
Copy the code

Then restart NPM Run serve again and check Network JS in your browser

Network JS

4. Code compression

(1) Install dependency: CNPM I -d uglifyjs-webpack-plugin

(2) Introduce dependencies at the top of vue.config.js

// const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
Copy the code

Exports configureWebpack added in vue.config.js module. Exports configureWebpack

// Configuration related to production environmentif(isProduction) {// Code compression config.plugins.push(new UglifyJsPlugin({uglifyOptions: { { warnings:false// If the package is wrong, comment this line drop_debugger:true,
                    drop_console: true,
                    pure_funcs: ['console.log']}},sourceMap: false,
            parallel: true}}))Copy the code

5. Enable Gzip

CNPM install –save-dev compression — webpack-plugin

(2) Introduce dependencies at the top of vue.config.js

// gzip const CompressionWebpackPlugin = require('compression-webpack-plugin')
Copy the code

Exports module. Exports configureWebpack (var. Config.js

// Configuration related to production environmentif(isProduction) {// code compression //.................. // gzip const productionGzipExtensions = ['html'.'js'.'css']
    config.plugins.push(
        new CompressionWebpackPlugin({
            filename: '[path].gz[query]',
            algorithm: 'gzip'.test: new RegExp(
                '\ \. (' + productionGzipExtensions.join('|') + '$'), threshold: 10240, // Only resources with a compression ratio smaller than this value will be processed.false// Delete original file}))}Copy the code

6. Pull out the common code

Exports module. Exports configureWebpack. Exports module. Exports configureWebpack

Optimization = {splitChunks: {cacheGroups: {vendor: {chunks:'all'.test: /node_modules/,
                name: 'vendor',
                minChunks: 1,
                maxInitialRequests: 5,
                minSize: 0,
                priority: 100
            },
            common: {
                chunks: 'all'.test: /[\\/]src[\\/]js[\\/]/,
                name: 'common',
                minChunks: 2,
                maxInitialRequests: 5,
                minSize: 0,
                priority: 60
            },
            styles: {
                name: 'styles'.test: /\.(sa|sc|c)ss$/,
                chunks: 'all',
                enforce: true
            },
            runtimeChunk: {
                name: 'manifest'}}}}Copy the code

Complete the vue. Config. Js

// const UglifyJsPlugin = require('uglifyjs-webpack-plugin'// gzip const CompressionWebpackPlugin = require('compression-webpack-plugin'Const isProduction = process.env.node_env! = ='development'// Whether the local environment requires CDN const devNeedCdn =true// CDN link const CDN = {// CDN: externals: {vue:'Vue',
        vuex: 'Vuex'.'vue-router': 'VueRouter'}, // CDN CSS link CSS: [], // CDN js link js: ['https://cdn.staticfile.org/vue/2.6.10/vue.min.js'.'https://cdn.staticfile.org/vuex/3.0.1/vuex.min.js'.'https://cdn.staticfile.org/vue-router/3.0.3/vue-router.min.js'
    ]
}

module.exports = {
    productionSourceMap: falseChainWebpack: config = > {/ / = = = = = = = = = = = = compressed images start = = = = = = = = = = = = config. The module. The rule ('images')
            .use('image-webpack-loader')
            .loader('image-webpack-loader')
            .options({ bypassOnDebug: true}). The end () / / = = = = = = = = = = = = compressed images end = = = = = = = = = = = = / / = = = = = = = = = = = = injection CDN start = = = = = = = = = = = = config. The plugin ('html'Tap (args => {// Inject a CDN only when it is required in the production environment or locallyif (isProduction || devNeedCdn) args[0].cdn = cdn
            returnThe args}) / / = = = = = = = = = = = = injection CDN start = = = = = = = = = = = =}, configureWebpack: config = > {/ / CDN way introduced, then the build time to ignore the related resourcesif(isProduction | | devNeedCdn) config. Externals. = the CDN externals / / production environment configurationif(isProduction) {// Code compression config.plugins.push(new UglifyJsPlugin({uglifyOptions: { { warnings:false// If the package is wrong, comment this line drop_debugger:true,
                            drop_console: true,
                            pure_funcs: ['console.log']}},sourceMap: false,
                    parallel: true})) // gzip const productionGzipExtensions = ['html'.'js'.'css']
            config.plugins.push(
                new CompressionWebpackPlugin({
                    filename: '[path].gz[query]',
                    algorithm: 'gzip'.test: new RegExp(
                        '\ \. (' + productionGzipExtensions.join('|') + '$'), threshold: 10240, // Only resources with a compression ratio smaller than this value will be processed.falseOptimization = {splitChunks: {cacheGroups: {vendor: {chunks:'all'.test: /node_modules/,
                            name: 'vendor',
                            minChunks: 1,
                            maxInitialRequests: 5,
                            minSize: 0,
                            priority: 100
                        },
                        common: {
                            chunks: 'all'.test: /[\\/]src[\\/]js[\\/]/,
                            name: 'common',
                            minChunks: 2,
                            maxInitialRequests: 5,
                            minSize: 0,
                            priority: 60
                        },
                        styles: {
                            name: 'styles'.test: /\.(sa|sc|c)ss$/,
                            chunks: 'all',
                            enforce: true
                        },
                        runtimeChunk: {
                            name: 'manifest'
                        }
                    }
                }
            }
        }
    }
}
Copy the code