简体   繁体   中英

Nuxt .env and import a js into a store

I have a somewhat large config.js file that I have created to for config type things. I am using a .env to keep secrets and such out of my github. In my .env file I have a variable called environment that I use to determine if I am on local, dev, stage, or prod. In my config.js file I am using that to load my certs and keys, and a bunch of other variables that are dependent on which environment I am on.

In one of my Vuex Store files, when I do the following it works

import config from '@/config'  
console.log(process.env.enviorment) // This logs out 'development' which i set in my .env file
const environ = config.developmemt

When I do the following I get 'environ is undefiend', even though I can see 'development' logged out.

import config from '@/config'  
console.log(process.env.enviorment) // This logs out 'development' which i set in my .env file
const environ = config[process.env.enviorment]

My VueEx file...

import config from '@/config'
console.log(process.env.enviorment) // <--- This is where it loads undefined at the app.js file which is my store, but loads the value in client.js
console.log(this.app) // <----------- this.app is undefined every time.
const environ = config.developmemt


export const state = () => (
{
 environment: eviron
}
)

You can use process.env only during build process. You want to use ENVs in runtime . In nuxt we have built-in ENVs handling: https://nuxtjs.org/docs/directory-structure/nuxt-config#runtimeconfig

In .env file add your ENVs:

ENVIRONMENT=staging

In nuxt.config.js you can use process.env.ENVIRONMENT, because it will be assigned during build time:

export default {
  publicRuntimeConfig: {
    environment: process.env.ENVIRONMENT
  },
};

Then you can get all your ENVs from publicRuntimeConfig during runtime (in vue and store files):

this.$config.environment

You can check my demo here: https://codesandbox.io/s/nuxt-envs-hx2cw?file=/pages/index.vue

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