前言

我们在搭建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,亲测有效,只需要修改成自己想要的文件名、路径即可。

推荐文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: