vue 项目打包通过命令修改 vue-router 模式 修改 API 接口前缀
需求说明:
在开发vue项目的过程中遇到的需求是要把api接口前缀暴露在命令行,通过npmrunbuildapiUrl即可修改接口入口,用于从docker部署到不同的测试服务器上,其次是路由模式的问题,部署到测试服务器上的需要是history模式,但是产品是用electron+vue开发的桌面应用,electron硬性要求vue-router的路由模式是hash模式,所以命令行需新增一个配置项mode,mode可选值有history、hash
最终结果:
npmrunbuild''hash ---> 使用源码中写死的api入口,vue-router模式是hash模式
npmrunbuildhttps://192.168.166.101:8444history ---> 使用https://192.168.166.101:8444作为api入口,vue-router模式是history模式
实现:
1.新建base/config.js用于存放从webpack.prod.conf.js里写入的数据
2.新建base/index.js用于将从base/config.js里导出的config挂载在Vue原型的$config对象上
3.新建build/apiConfig.js用于封装fs-extra对文件的读写
4.在webpack.prod.conf.js将命令行中敲入的命令写入base/config.js里
5.在main.js中将base/index.js抛出的install挂载到Vue上
6.在Login.vue和router/index.js里引入this.$config.host以及base/config.js即可
关键代码:
2.新建base/index.js用于将从base/config.js里导出的config挂载在Vue原型的$config对象上
//将config封装成插件
//examplethis.$config
//导入所有接口
importconfigfrom'./config';
constinstall=Vue=>{
if(install.installed)
return;
install.installed=true;
Object.defineProperties(Vue.prototype,{
//此处挂载在Vue原型的$config对象上
$config:{
get(){
returnconfig;
}
}
})
}
exportdefaultinstall;
3.新建build/apiConfig.js用于封装fs-extra对文件的读写
constfs=require("fs-extra");
constpath=require("path");
var_path=path.join(__dirname,"../src/base/host.js");
if(!fs.pathExistsSync(_path)){
//如果不存在路径
fs.mkdirpSync(_path);//就创建
}
module.exports={
read:function(){
letfilesData=fs.readFileSync(_path,"utf-8",function(e,data){
if(e)throwe;
returndata;
});
returnfilesData;
},
write:function(writeStr){
fs.open(_path,"w",function(e,fd){
if(e)throwe;
fs.write(fd,writeStr,0,"utf8",function(e){
if(e)throwe;
fs.closeSync(fd);
});
});
}
};
4.在webpack.prod.conf.js将命令行中敲入的命令写入base/config.js里
constapiConfig=require('./apiConfig');
apiConfig.read();
apiConfig.write(
`exportconsthost='${process.argv[2]}';
exportconstmode='${process.argv[3]}';
//默认全部倒出
//根绝需要进行
exportdefault{
host,
mode
}`
);
5.在main.js中将base/index.js抛出的install挂载到Vue上
importhostfrom'./base/index'; Vue.use(host);
6.在Login.vue里引入this.$config.host
this.$store.set("presetPort",this.$config.host?this.$config.host.split(":")[2]:"443");//设置预置端口
this.$store.set("presetHost",this.$config.host?this.$config.host.split(":")[0]:"https");//设置预置协议
this.$store.set("presetIP",this.$config.host?this.$config.host.split(":")[1].split("/")[2]:"192.168.166.109");//设置预置IP
6.在router/index.js里引入base/config.js
import{mode}from'@/base/config';
letrouter=null;
letroutes=[
{
path:'xxx',
name:'xxx',
component:xxx
}...];
mode==='history'?routes.push({path:"*",component:xxx}):"";
router=newRouter({
mode:mode,
routes:routes
})
exportdefaultrouter;
总结
以上所述是小编给大家介绍的vue项目打包通过命令修改vue-router模式修改API接口前缀,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。