简体   繁体   中英

Nuxt, doesnt load NUXT_ENV var

Hello I have an env var like the following in the nuxt.config.js

env: {
   BAR: process.env.BAR
}

The problem is that I need to load from os env var instead of .env file so I tried to use NUXT_ENV_ like this:

I load the env var with

export NUXT_ENV_BAR='value'

1 Try

env: {
   BAR: process.env.NUXT_ENV_BAR
}
....
console.log(process.env.BAR)
....

2 Try

....
env: {
   NUXT_ENVBAR: process.env.NUXT_ENV_BAR
}
console.log(process.env.NUXT_ENVBAR)
....

I tried the same with publicRuntimeConfig instead of env , but didn't work too.

How can I set os env var inside nuxt.js app?

Thanks

When you set an object in JSON the format is key : value . You can not use = .

So your code should be:

env: {
   BAR: process.env.BAR
}

To manage your custom Nuxt env you can use https://github.com/nuxt-community/dotenv-module dotenv module or publicRuntimeConfig as you said.

If you want to use the 'publicRuntimeConfig' attribute in your nuxt.config.js file just implement this code:

 publicRuntimeConfig: {
   BAR: 'yourValue',
 }

Then you can access this config data with $config as $config.BAR . (To test your config in your browser just write __NUXT__.config in the console tab)

You could create a file eg serverVariables.js with the server variables that you want to define at the location of your choice in your project.

export default {
  BAR: process.env.BAR || '<your default value>',
};

Next, inside your nuxt.config.js , you could import those variables at the very top like;

import serverVariables from '~/serverVariables';

Next you could map those variables to your publicRuntimeConfig like;

publicRuntimeConfig: {
    BAR: serverVariables.BAR,
}

You could then access it anywhere in your components like;

$config.BAR

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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