Vue project packaging optimization and configuration vue.config.js file (useful for actual measurement)

First we need to create a vue.config.js in the root directory

insert image description here

First write in the file first

//打包配置文件
module.exports = {
    assetsDir: 'static',     //  outputDir的静态资源(js、css、img、fonts)目录
    publicPath: './',   // 静态资源路径(默认/,如果不改打包后会白屏)
    productionSourceMap: false, //不输出map文件
};

Then use CDN to speed up optimization (this code is outside the module.exports object)

For cdn acceleration, you can go to the official website to find the path of the corresponding plug- in BootCDN official website

// 是否为生产环境
const isProduction = process.env.NODE_ENV !== 'development';

// 本地环境是否需要使用cdn
const devNeedCdn = false

// cdn链接
const cdn = {
    // cdn:模块名称和模块作用域命名(对应window里面挂载的变量名称)
    externals: {
        'vue': 'Vue',
        'vuex': 'Vuex',
        'vue-router': 'VueRouter',
        'axios': 'axios',
        'element-ui': 'ELEMENT'  //这里需要注意下
    },
    // cdn的css链接
    css: [
		'https://unpkg.com/element-ui/lib/theme-chalk/index.css'  //引入element ui  css文件
    ],
    // cdn的js链接
    js: [
        'https://cdn.bootcss.com/vue/2.6.11/vue.min.js',
        'https://cdn.bootcss.com/vue-router/3.2.0/vue-router.min.js',
        'https://cdn.bootcss.com/axios/0.27.2/axios.min.js',
        'https://cdn.bootcdn.net/ajax/libs/echarts/5.3.3/echarts.common.min.js'
    ]
}

Write in the module.exports object

    chainWebpack: config => {
        // ============注入cdn start============
        config.plugin('html').tap(args => {
            // 生产环境或本地需要cdn时,才注入cdn
            if (isProduction || devNeedCdn) args[0].cdn = cdn
            return args
        })
        // ============注入cdn start============
    },

Compress image files

Download dependencies If you use npm here, the download speed may be slow and the installation may fail. It is recommended to use cnpm

cnpm install image-webpack-loader --save-dev

Then continue to add the following code in chainWebpack

        config.plugins.delete('prefetch')
        config.module.rule('images')
            .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
            .use('image-webpack-loader')
            .loader('image-webpack-loader')
            .options({ bypassOnDebug: true })

compress the code

It is also recommended to use cnpm to download dependencies first

cnpm install uglifyjs-webpack-plugin --save-dev

Write in the module.exports object

 configureWebpack: config => {
        if (isProduction || devNeedCdn) config.externals = cdn.externals
        // 代码压缩
        config.plugins.push(
            new UglifyJsPlugin({
                uglifyOptions: {
                    //生产环境自动删除console
                    compress: {
                        drop_debugger: true,
                        drop_console: true,
                        pure_funcs: ['console.log']
                    }
                },
                sourceMap: false,
                parallel: true
            })
        )
    },

Extract from common code

Continue to write in configureWebpack

        // 公共代码抽离
        config.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'
                    }
                }
            }
        }

Finally integrate vue.config.js

const UglifyJsPlugin = require('uglifyjs-webpack-plugin')


// 是否为生产环境
const isProduction = process.env.NODE_ENV !== 'development';

// 本地环境是否需要使用cdn
const devNeedCdn = false

// cdn链接
const cdn = {
    // cdn:模块名称和模块作用域命名(对应window里面挂载的变量名称)
    externals: {
        'vue': 'Vue',
        'vuex': 'Vuex',
        'vue-router': 'VueRouter',
        'axios': 'axios'
    },
    // cdn的css链接
    css: [

    ],
    // cdn的js链接
    js: [
        'https://cdn.bootcss.com/vue/2.6.11/vue.min.js',
        'https://cdn.bootcss.com/vue-router/3.2.0/vue-router.min.js',
        'https://cdn.bootcss.com/axios/0.27.2/axios.min.js',
        'https://cdn.bootcdn.net/ajax/libs/echarts/5.3.3/echarts.common.min.js'
    ]
}

//打包配置文件
module.exports = {
    assetsDir: 'static',
    publicPath: './',
    productionSourceMap: false, //不输出map文件

    chainWebpack: config => {
        // ============注入cdn start============
        config.plugin('html').tap(args => {
            // 生产环境或本地需要cdn时,才注入cdn
            if (isProduction || devNeedCdn) args[0].cdn = cdn
            return args
        })
        // ============注入cdn start============

        // 在chainWebpack中新增以下代码
        config.plugins.delete('prefetch')
        config.module.rule('images')
            .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
            .use('image-webpack-loader')
            .loader('image-webpack-loader')
            .options({ bypassOnDebug: true })

    },

    configureWebpack: config => {
        if (isProduction || devNeedCdn) config.externals = cdn.externals
        // 代码压缩
        config.plugins.push(
            new UglifyJsPlugin({
                uglifyOptions: {
                    //生产环境自动删除console
                    compress: {
                        drop_debugger: true,
                        drop_console: true,
                        pure_funcs: ['console.log']
                    }
                },
                sourceMap: false,
                parallel: true
            })
        )

        // 公共代码抽离
        config.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'
                    }
                }
            }
        }
    },

    devServer: {
        proxy: {
            '/api': {
                target: '线上接口地址',
                ws: true,
                changeOrigin: true,
                pathRewrite: {
                    '^/api': '/', // 根据之前vuejs的配置,用来拿掉URL上的(/api),但是暂时没有什么效果
                },
            },
        },
    },

};

Finally, my vue project was reduced from the original 12M to 2M, and the startup was also successful

Guess you like

Origin blog.csdn.net/weixin_46824709/article/details/126034991
Recommended