在 Vue 项目中,vue.config.js 同时配置代理和别名
在 Vue 项目中,vue.config.js 文件是用于配置 Vue CLI 项目的一些选项,例如代理(proxy)和别名(alias)。如果你想同时配置代理和别名,可以按照以下方式进行设置。
1. 安装和配置 vue.config.js
首先,确保你的项目中存在 vue.config.js 文件。如果没有,你可以在项目根目录下创建一个。
2. 配置代理(Proxy)
在 vue.config.js 中,你可以使用 devServer 对象来配置开发服务器的代理。例如,如果你希望将 /api 的请求代理到 http://localhost:3000,可以这样配置:
module.exports = {devServer: {proxy: {'/api': {target: 'http://localhost:3000',changeOrigin: true,pathRewrite: { '^/api': '' }}}}
}
3. 配置别名(Alias)
在同一个 vue.config.js 文件中,你也可以使用 configureWebpack 或 chainWebpack 来配置 webpack 的别名。例如,如果你希望将 @ 指向 src 目录,可以这样配置:
使用 configureWebpack
module.exports = {configureWebpack: {resolve: {alias: {'@': path.resolve(__dirname, 'src')}}}
}
使用 chainWebpack(推荐方式)
const path = require('path');module.exports = {chainWebpack: config => {config.resolve.alias.set('@', path.resolve(__dirname, 'src'))}
}
4. 结合使用代理和别名
你可以将代理和别名配置结合在同一个 vue.config.js 文件中,如下所示:
const path = require('path');module.exports = {devServer: {proxy: {'/api': {target: 'http://localhost:3000',changeOrigin: true,pathRewrite: { '^/api': '' }}}},configureWebpack: {resolve: {alias: {'@': path.resolve(__dirname, 'src')}}}// 或者使用 chainWebpack 配置别名,如上所示的第二种方式。
}
或
const path = require("path");
const webpack = require('webpack');
// 拼接路径
const resolve = (dir) => require('path').join(__dirname, dir)module.exports = {assetsDir: 'static',// 放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录productionSourceMap: false, //如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。devServer: {host: "0.0.0.0",port: 8080, // 端口号https: false, // https:{type:Boolean}open: true, // 配置自动启动浏览器 open: 'Google Chrome'-默认启动谷歌// 配置多个代理proxy: {"/api": {target: "http://localhost:3000",ws: true, //代理的WebSocketschangeOrigin: true, // 允许websockets跨域pathRewrite: { '^/api': '' } // 移除路径中的/farm前缀}},before: (app) => {app.use((req, res, next) => {console.log('代理请求路径:', req.originalUrl); // 打印原始请求路径console.log('代理目标地址:', this.proxy); // 打印代理目标next();});}},chainWebpack: config => {config.resolve.alias.set('@', path.resolve(__dirname, 'src'))}}通过以上设置,你可以同时配置开发服务器的代理和 webpack 的别名。这样,你的 Vue 项目就可以在开发环境中更方便地管理和使用 API 以及模块路径了
