vue项目打包优化及配置vue.config.js文件(实测有用)

首先我们需要在根目录里创建一个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,启动也是成功

  • 9
    点赞
  • 61
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
引用中的代码中,首先使用module.exports将配置对象导出,然后设置了assetsDir、publicPath、productionSourceMap等选项,以及引入了一些CDN链接来加速优化。这些配置可以根据具体需求进行修改和定制。引用也提供了一些常见的配置选项,如publicPath、assetsDir、outputDir等。这些配置选项可以根据具体需求进行调整。 根据你提供的代码,可以看出你的vue项目中未包含vue.config.js文件。可能的原因有两种: 1. 你的项目中没有创建vue.config.js文件。你可以在项目根目录下手动创建一个vue.config.js文件,并在其中编写你需要的打包配置。 2. 你的vue.config.js文件存在,但是文件路径不正确。请确保vue.config.js文件位于你的Vue项目的根目录下,并确保文件名拼写正确。 请确认以上两点,如仍然无法解决问题,请提供更多细节,以便进一步协助。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [vue项目打包优化配置vue.config.js文件实测有用)](https://blog.csdn.net/weixin_46824709/article/details/126034991)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *3* [vue打包文件配置说明vue.config.js](https://blog.csdn.net/weixin_47970316/article/details/126095427)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值