问题
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/'
}
]
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.
回答1:
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 };
Imported that file in nuxt.config.js
as below
let appEnv = process.env.NODE_ENV || 'development';
import { MasterKeys } from './config.js';
Now, whenever I want to use apiEndPoint
value in nuxt.config.js I will access as MasterKeys[appEnv].apiEndPoint
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
}
And then in components, I can access that value as process.env.apiEndPoint
And to will declare env in package.json
as below
"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!!!!
回答2:
Create two separate config files and import them with condition and use inside nuxt config as follows
const CONFIG = process.env.NODE_ENV === 'development' ? require('dev-config') : require('prod-config');
module.exports = {
axios: {
baseURL: CONFIG.API_BASE
}
}
来源:https://stackoverflow.com/questions/60451671/using-different-env-for-different-cases-in-nuxt