在nuxt中针对不同情况使用不同的环境 [英] using different env for different cases in nuxt
问题描述
我是Nuxt或任何种类的节点人员的新手,我试图为不同的情况创建不同的环境,例如如果我想测试我的应用,我想运行dev对象块(指向dev端点)等,下面是一个示例
I am new to Nuxt or any sort of node stuff.I m trying to create different environment for different cases, e.g. If I want to test my app, I want the block of dev object to run (pointing to dev endpoint) etc, following is a example
[
prod: {
server: www.mysite.com,
api: 'www.jsonplaceholder.com/'
},
dev: {
server: www.internal-mysite.com,
api: 'www.jsonplaceholder.com/'
}
]
所以当我执行 npm run dev
时,它将使用那些我知道 .env
不允许对象或数组,所以我不能使用它。我尝试了 dotenv
,但是获得的帮助不多在其中,我尝试观看此,但我无法通过NODE_ENV = config.dev(假设config是包含对象的文件)如何使我的应用程序像这样工作?
so when I do npm run dev
, it run the app with those endpoints I know that .env
won't allowed objects or array so I cannot use that .I have tried dotenv
but not much help I can get out of it, I tried watching this but I cannot pass NODE_ENV=config.dev (given that config is a file containing the object) How can I make my app to work like that?
详细的回答将有所帮助。
A detailed answered would be helpful.
推荐答案
我已经创建了一个 config.js
与下面相同
I Have created one config.js
same as below
const MasterKeys = {
development: {
apiEndPoint: 'example.com',
clientId: '1234567',
clientSecret: '11111111'
},
staging: {
apiEndPoint: 'staging.example.com',
clientId: '1234567',
clientSecret: '11111111'
},
production: {
apiEndPoint: 'prod.example.com',
clientId: '1234567',
clientSecret: '11111111'
}
};
export { MasterKeys };
将该文件导入 nuxt.config.js
如下所示
let appEnv = process.env.NODE_ENV || 'development';
import { MasterKeys } from './config.js';
现在,每当我想使用 apiEndPoint
我将以 MasterKeys [appEnv] .apiEndPoint
Now, whenever I want to use apiEndPoint
value in nuxt.config.js I will access as MasterKeys[appEnv].apiEndPoint
访问nuxt.config.js中的值使用组件中 config.js
中的任何配置键,我将使用 nuxt.config.js
的env属性,如下例。
And if I want to use any configuration key from config.js
in component I will use env property of nuxt.config.js
as below example.
env: {
apiEndPoint: MasterKeys[appEnv].apiEndPoint,
clientId: MasterKeys[appEnv].clientId
}
然后在组件中,我可以将该值作为 process.env.apiEndPoint
And then in components, I can access that value as process.env.apiEndPoint
然后在 package.json $ c中声明env $ c>如下
"scripts": {
"dev": "nuxt",
"stagingbuild": "NODE_ENV=staging nuxt build",
"staging": "NODE_ENV=staging nuxt start",
"build": "NODE_ENV=production nuxt build",
"start": "NODE_ENV=production nuxt start"
}
希望这对您有帮助!!!
Hope this will help you!!!!
这篇关于在nuxt中针对不同情况使用不同的环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!