vue3项目vue.config.js配置“代理”、“端口”、“打包名”、“图片压缩”

前言

我们在搭建vue3项目的时候不可避免的会遇到“代理”、“端口”、“打包名”、“图片压缩”等配置问题,本文逐一讲述该怎么样在vue.config.js中去配置。


一、配置代理端口和代理转发

const {defineConfig} = require('@vue/cli-service')

module.exports = defineConfig({
    devServer: {
        host: 'localhost',
        port: 3000,  // 启动端口号
        proxy: {
            '/api': { // 请求接口中要替换的标识
                target: 'http://117.62.22.235:17009', // 代理地址
                ChangeOrigin: true, // 是否允许跨域
                secure: true,
                pathRewrite: {
                    '^/api': '' // 这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可
                }
            }
        }
    }
})


二、修改打包名

const {defineConfig} = require('@vue/cli-service')

module.exports = defineConfig({
    publicPath: './', // 打包位置
    outputDir: 'distBigScreenForBase' // 包名
})

三、图片压缩

图片压缩先要引入image-webpack-loader插件

命令:npm install image-webpack-loader --save-dev

const {defineConfig} = require('@vue/cli-service')

module.exports = defineConfig({
    // 图片压缩
    chainWebpack: config => {
        const imagesRule = config.module.rule('images')
        imagesRule
            .use('image-webpack-loader')
            .loader('image-webpack-loader')
            .options({
                bypassOnDebug: true
            })
            .end()
    }
})

四、完整代码

const {defineConfig} = require('@vue/cli-service')

module.exports = defineConfig({
    publicPath: './', // 打包位置
    outputDir: 'distBigScreenForBase', // 包名
    devServer: {
        host: 'localhost',
        port: 3000,  // 启动的端口号
        proxy: {
            '/api': { // 请求接口中要替换的标识
                target: 'http://117.62.22.235:17009', // 代理地址
                ChangeOrigin: true, // 是否允许跨域
                secure: true,
                pathRewrite: {
                    '^/api': '' // 这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可
                }
            }
        }
    },
    // 图片压缩
    chainWebpack: config => {
        const imagesRule = config.module.rule('images')
        imagesRule
            .use('image-webpack-loader')
            .loader('image-webpack-loader')
            .options({
                bypassOnDebug: true
            })
            .end()
    },
})

总结

vue3的配置和vue2有所不同,不能照搬照套vue2,那样会报错。这里没有用vite,用的是vue cli,所以在vue.config.js中配置。如果是vite项目则在vite.config.js,具体可参考https://mp.csdn.net/mp_blog/creation/editor/131852773 代码可以直接copy,亲测有效,只需要修改成自己想要的文件名、路径即可。

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值