在vue开发项目后,一般会使用webpack将前端项目打包成dist文件夹,但是在开发过程中可能存在某些配置项需要动态配置,如果每次修改配置都得修改代码后重写打包,这样会增加很多工作量。
在vue-cli项目中,public文件夹下的静态资源是不会经过 webpack 打包处理的,因此,我们可以将项目中需要动态修改的内容抽离成一个配置文件,将该文件放在public文件夹下,每次修改就只需更改该配置文件,无需重新打包。
本文以vue2和typescript为例。
1 新建配置文件
在public文件夹下新建一个config文件夹,文件夹下新建json文件 globalConfig.json。
将项目中需要动态配置的内容抽离出来,写在 globalConfig.json 中。
2 在入口文件请求配置文件的内容
在入口文件src文件夹下的main.ts文件中请求配置文件的内容,并将它添加到Vue.prototype的变量中,这样就可以在所有vue实例中使用。
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import axios from "axios";
function getGlobalConfig() {
return new Promise((resolve, reject) => {
let baseUrl = location.protocol + "//" + location.host;
axios.get(`${baseUrl}/config/globalConfig.json`).then((result) => {
console.log("getGlobalConfig", result);
Vue.prototype["globalConfigs"] = result;
resolve(result);
});
});
}
async function main() {
await getGlobalConfig();
new Vue({
router,
store,
render: (h) => h(App),
}).$mount("#app");
}
main();
3 在项目中使用
test(){
let userService = this["globalConfigs"].userService;
console.log(userService)
}