首先我们需要在根目录里创建一个vue.config.js

在这里插入图片描述

首先在文件中先写入

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

之后再使用CDN 加速优化(此代码在module.exports对象外面)

cdn加速可以去官网找到相应插件的路径 BootCDN官网
// 是否为生产环境
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'
    ]
}

在module.exports对象里写入

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

对图片文件进行压缩

下载依赖 这里如果用npm 可能会下载速度慢安装失败,建议使用cnpm

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

之后继续在 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 })

对代码压缩

先下载依赖 也建议使用cnpm

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

在module.exports对象里写入

 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
            })
        )
    },

对公共代码抽离

在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'
                    }
                }
            }
        }

最后整合起来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),但是暂时没有什么效果
                },
            },
        },
    },

};

最后我的vue项目由原来的12M减少到2M,启动也是成功

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐