【问题标题】:Vue-router & webpack: configure routes using environment variables at build timeVue-router & webpack:在构建时使用环境变量配置路由
【发布时间】:2018-03-13 19:08:47
【问题描述】:

我有一个用于多个部署的 vue.js 应用程序。对于一种部署,url 应该是<domian>/。但是,对于其他人,它可能需要为<domain>/tool。这些路由将使用环境变量设置:TOOL_ROUTE=/TOOL_ROUTE=/tool

问题是,使用 vue-router,我需要在 main.js 中指定工具应该从 url 获得什么:

require('babel-polyfill');
var Vue = require('vue');
var VueRouter = require('vue-router');
var Vuex = require('vuex');
var sync = require('vuex-router-sync').sync;
var App = require('./vue/App.vue');
var Content = require('./vue/Content.vue');
var Configurator = require('./vue/components/Configurator.vue');
var store = require('./vue/store/store.js');

var router;

Vue.use(Vuex);
Vue.use(VueRouter);

router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/tool', component: Content, name: 'home' },
    { path: '/tool/config', component: Configurator, name: 'config' }
  ]
});

sync(store, router);

new Vue({
  router: router,
  store: store,
  render: h => h(App)
}).$mount('#app');

有没有办法在编译时将/tool 替换为环境变量的值?

【问题讨论】:

  • 你的意思是process.env.TOOL_ROUTE
  • 是的。我正在寻找一种将其纳入 js 的好方法。相对较新的 webpack。
  • 我不确定问题出在哪里,因为这就是您在 main.js 文件中检索环境变量的方式。这是process.envnodejs.org/api/process.html#process_process_env上的文档
  • 如果我在env中设置TOOL_ROUTE然后修改main.js使用{ path: process.env.TOOL_ROUTE, component: Content, name: 'home'},这里定义的路由是path: undefined
  • TOOL_ROUTE 的设置如何?

标签: webpack vue.js vue-router


【解决方案1】:

您必须在 webpack 构建期间转发环境变量。您可以像设置 NODE_ENV 变量一样执行此操作。

var route = process.env.TOOL_ROUTE || '/tool'; // default value if the variable isn't set

route = '"' + route + '"'; // encapsulate with "

console.log('Tool route:', route);

module.exports = {
  NODE_ENV: '"production"',
  TOOL_ROUTE: route // make sure it is exported
}

您现在可以访问代码中的值:

routes: [
    { path: process.env.TOOL_ROUTE, component: Content, name: 'home' },
    { path: process.env.TOOL_ROUTE + '/config', component: Configurator, name: 'config' }
  ]

注意:对于 vue-cli webpack 模板,请在 config/prod.env.js 中执行此操作。这将在devtest 环境中合并。

考虑到每次环境变量的值发生变化时您都需要构建!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 2017-07-07
    • 1970-01-01
    相关资源
    最近更新 更多