vue实现不同服务器代理,接上篇,虽然可实现多版本代理,但是每增加一种模式就需要重下新修改vue.config.js以及.env.dev.local,感觉很不智能,扩展性挺差。主要实现思路:
在.gitignore中添加
现新建项目,目录结构如下:
development/config/config.local
development/config/config.*.local
development/config 下的config.development.dev
{
"/api":"http://serverurl"
}
development/config 下的config.owndev.dev
{
"/api/login":"http://localhost:8080",
"/api/register":"http://localhost:8081"
}中devDependencies即可
"devDependencies": {
"cross-env": "^5.2.0"
}
"script":{
"serve": "cross-env BUILD_ENV=development vue-cli-service serve",
"owndev": "cross-env BUILD_ENV=owndev vue-cli-service serve",
}
var path = require('path'); //系统路径模块
var fs = require('fs'); //文件模块
const defaultProxy = {
"/api":"http://serverUrl"
};
//根据当前的运行环境判断走哪个配置
const DEVELOPMENT = "development"
let currentEnv = process.env.BUILD_ENV?process.env.BUILD_ENV:DEVELOPMENT
let configPath = `config/config.${currentEnv}.local`
let filePath = path.join(__dirname, configPath); //文件路径,__dirname为当前运行js文件的目录
let proxyContent = null;
//读取json文件,异步
/*fs.readFile(filePath, 'utf-8', function(err, data) {
if (!err) {
proxyContent = data;
}
});*/
//将json字符串转化为json对象
try{
proxyContent = JSON.parse(fs.readFileSync(filePath,'utf-8'))
}catch(e){
proxyContent = defaultProxy
}
if(proxyContent == null){
proxyContent = defaultProxy
}
let proxys = {}
//遍历所有的配置代理,对应不同的服务器
Object.getOwnPropertyNames(proxyContent).forEach(function (key) {
let targetPath = proxyContent[key]
let proxyItem = {};
proxyItem.target = targetPath;
proxyItem.ws = true;
proxyItem.changeOrigin = true;
proxyItem.pathRewrite = {}
proxyItem.pathRewrite[`^${key}`] = '/'
proxys[key] = proxyItem
});
module.exports = proxys
let proxy = require('./development/proxy/proxy')
let config = {
publicPath:"/" ,
devServer: {
port: 8080,
proxy:proxy
}
}
module.exports = config文件即可,即使增加了代理也可只增加配置文件完成代理。总结
以上所述是小编给大家介绍的vue配置文件实现代理v2版本的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对自学php网网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!