共计 1799 个字符,预计需要花费 5 分钟才能阅读完成。
前言
我们在搭建 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,亲测有效,只需要修改成自己想要的文件名、路径即可。
原文地址: vue3 项目 vue.config.js 配置“代理”、“端口”、“打包名”、“图片压缩”
正文完