[英]How to use different settings in nuxt.config.js depending on the environment
Thanks to dotenv I can use environment variables in my nuxt.config.js file感谢 dotenv 我可以在我的 nuxt.config.js 文件中使用环境变量
Only I have whole settings that need to disappear depending on the environment.只有我有整个设置需要根据环境消失。 In some cases, I know how to use a tertiary condition, but in others, I cannot.
在某些情况下,我知道如何使用第三条件,但在其他情况下,我不能。
For example, for my dev environment, I have to do this:例如,对于我的开发环境,我必须这样做:
export default {
head: {
title: process.env.APP_NAME,
},
modules: [
// https://go.nuxtjs.dev/axios
'@nuxtjs/axios',
'@nuxtjs/auth',
'@nuxtjs/dotenv'
],
axios: {
baseURL: 'http://app.test/api',
},
…
}
And for my production environment I have to add some things对于我的生产环境,我必须添加一些东西
export default {
head: {
title: process.env.APP_NAME,
},
modules: [
// https://go.nuxtjs.dev/axios
'@nuxtjs/axios',
'@nuxtjs/auth',
'@nuxtjs/dotenv',
'@nuxtjs/proxy'
],
axios: {
prefix: '/api/',
proxy: true
},
// also a new bloc
proxy: {
'/api/': {
target: 'https://my-api.app/'
}
},
…
}
How to do that simply?如何简单地做到这一点?
The Nuxt config file is simply a normal .js
file. Nuxt 配置文件只是一个普通的
.js
文件。
You can create and modify the exported object the same as any other object.您可以像任何其他 object 一样创建和修改导出的 object。
const isProd = true;
const nuxtConfig = {
head: {
title: process.env.APP_NAME,
},
modules: [
// https://go.nuxtjs.dev/axios
'@nuxtjs/axios',
'@nuxtjs/auth',
'@nuxtjs/dotenv'
],
axios: {
baseURL: 'http://app.test/api',
},
};
if(isProd) {
nuxtConfig.modules.push('@nuxtjs/proxy');
nuxtConfig.axios.proxy = true;
nuxtConfig.proxy = {
'/api/': {
target: 'https://my-api.app/'
}
}
}
export default nuxtConfig;
If you only have minimal differences between environments, maintain the default nuxt.config.js
structure and just use inline conditions (ie ternary operator ) wherever you need.如果环境之间的差异很小,请保持默认的
nuxt.config.js
结构,并在需要的任何地方使用内联条件(即三元运算符)。
Example:例子:
head: {
title: process.env.NODE_ENV === 'prod' ? "my prod title" : "my dev title"
}
You can also chain multiple conditions...您还可以链接多个条件...
head: {
title: process.env.NODE_ENV === 'prod1' ? "my prod title 1" : process.env.NODE_ENV === 'prod2' ? "my prod title 2" : "my dev title"
}
... however now you have more complexity. ...但是现在你有更多的复杂性。 If it gets too deep, then maybe it's time to have logic outside of the main export object, as @Jordan suggested.
如果它变得太深,那么也许是时候在主要导出 object 之外设置逻辑了,正如@Jordan 所建议的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.