【发布时间】:2020-08-29 11:25:58
【问题描述】:
关注https://nuxtjs.org/api/configuration-env
我一直在尝试为整个项目在nuxt.config.js once 中设置我的 apiUrl,例如:
export default {
env: {
apiUrl: process.env.MY_REMOTE_CMS_API_URL || 'http://localhost:1337'
}
}
在 nuxt.config.js 中添加它,我希望(并且希望)在项目中 任何地方 都可以访问 apiUrl . 特别是以下 3 种情况需要它:
-
使用 axios,从动态 url 生成静态页面(在
nuxt.config.js中)generate: { routes: function () { return axios.get(apiUrl + '/posts') .then((res) => { return res.data.filter(page => { return page.publish === true; }).map(page => { return { route: '/news/' + page.slug } }) }) } }, -
使用 apollo,通过 graphql 获取数据(in
nuxt.config.js)apollo: { clientConfigs: { default: { httpEndpoint: apiUrl + '/graphql' } } }, -
在每个布局、页面和组件中,作为媒体的基本网址:
<img :src="apiUrl + item.image.url" />
如您所见,我只需要“打印”cms 的实际基本网址。
我也试过用process.env.apiUrl访问它,没有成功。
我能够做到这一点的唯一方法是创建一个额外的 plugin/apiUrl.js 文件,该文件注入 api url,这对我来说似乎是错误的,因为我现在在我的项目中设置了 apiUrl 两次。
我过去问过这个问题,但方式不太清楚。有人建议我使用 dotenv,但从文档来看,它看起来像添加了额外的复杂层,这对于更简单的设置可能不是必需的。 谢谢。
【问题讨论】:
标签: vue.js axios environment-variables nuxt.js apollo