简体   繁体   English

根据nuxt.config.js中的服务器创建动态环境变量

[英]Create dynamic env variables based on the server inside nuxt.config.js

I have added below ENV data inside nuxt.config.js file 我在nuxt.config.js文件中添加了以下ENV数据

env: {
      apiUrl: 'http://mywebsite.local/api/',
      webUrl: 'http://mywebsite.local/',

      apiUrl: 'https://mywebsite.live/api/',
      webUrl: 'https://mywebsite.live/'
},

Depending on the environment, I keep the 2 lines commented. 根据环境,我保留两行注释。 So when I am working locally, I comment the 2 lines with mywebsite.live url. 因此,当我在本地工作时,我用mywebsite.live url注释了这两行。 And when the files are uploaded to server, I comment the 2 lines with url mywebsite.local. 当文件上传到服务器时,我用URL mywebsite.local注释了两行。

What I want to do is that the code should detect if the site is running locally or on the server and use the ENV configs based on that. 我想做的是代码应该检测该站点是在本地运行还是在服务器上运行,并基于此使用ENV配置。 How can I do that? 我怎样才能做到这一点?

You can tell if you're in production or development with this env variable: process.env.NODE_ENV which you can use in the ternary operator to solve your problem. 您可以使用以下env变量来判断您是在production还是developmentprocess.env.NODE_ENV ,可以在三元运算符中使用它来解决问题。

env: {
  apiUrl: process.env.NODE_ENV === "production" ? 'https://mywebsite.live/api/' : 'http://mywebsite.local/api/',
  webUrl: process.env.NODE_ENV === "production" ? 'https://mywebsite.live/' : 'http://mywebsite.local/'
}

Instead of hard-coding your environment variables into nuxt.config, I'd recommend checking out this dotenv nuxt module or using dotenv itself . 建议您不要签出此dotenv nuxt模块或使用dotenv本身 ,而不是将环境变量硬编码到nuxt.config中。

This way, you can have actual .env files setup on each environment you need, or, if you're using Netlify or something as such for your deployments, you can set up your environment keys using their tools too. 这样,您可以在所需的每个环境中设置实际的.env文件,或者,如果您使用Netlify或类似的部署环境,也可以使用其工具来设置环境密钥。

This would also avoid nested if-else statements if you start having multiple environments and will keep your code cleaner. 如果您开始具有多个环境,这还将避免嵌套的if-else语句,并使代码更整洁。

If you still want to hard-code it, then you could do what was already suggested in here and use if/else or ternary operations inside your nuxt-config, like: 如果仍要对其进行硬编码,则可以执行此处已建议的操作,并在nuxt-config中使用if / else或三元操作,例如:

env: {
  apiUrl: process.env.NODE_ENV === "production" ? 'https://mywebsite.live/api/' : 'http://mywebsite.local/api/',
  webUrl: process.env.NODE_ENV === "production" ? 'https://mywebsite.live/' : 'http://mywebsite.local/'
}

But then again, I do not recommend this approach. 但是话又说回来,我推荐这种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM