Can not access process.env variables in component nuxt

前端 未结 3 859
广开言路
广开言路 2021-01-18 01:09

In nuxt config I have env object

env: {
    hey: process.env.hey || \'hey\'
},

as soon as I want to display it in component template:

相关标签:
3条回答
  • 2021-01-18 01:39

    process isn't directly available to templates, but you can access it by creating a computed property or adding it to your component's state. Here's an example:

    <template>
      <div>{{ message }}</div>
    </template>
    
    export default {
      computed: {
        message() {
          return process.env.hey;
        },
      },
    };
    
    0 讨论(0)
  • 2021-01-18 01:47

    Vue components do not have access to environment variables directly. Think of it as Vue being client side and environment variables being on server side.

    There is probably several ways to get around this. If you are using webpack, this is one option:

    https://webpack.js.org/plugins/define-plugin/

    You could define the environment variable as a global variable on the client side.

    0 讨论(0)
  • 2021-01-18 02:00

    Here's how you can grab environment variables in a nuxt component.

    First you must create a serverInit.js file in your Vuex Store. Because process.env is rendered server side, you must call it in the part of your app that is also rendered server-side....in this case, Vuex.

    const state = () => ({
      env: {},
      buildEnv: '',
    })
    
    const mutations = {
      setEnv(state, env) {
        state.env = env
      },
      setBuildEnv(state, env) {
        state.buildEnv = env
      },
    }
    
    const actions = {
      nuxtServerInit({ commit }) {
        if (process.server) {
          if (process.env.NUXT_ENV_BUILD_HASH) {
            commit('setEnv', {
              buildHash: JSON.parse(process.env.NUXT_ENV_BUILD_HASH),
            })
          } else {
            commit('setEnv', {
              buildHash: false,
            })
          }
          commit('setBuildEnv', process.env.NODE_ENV)
        }
      },
    }
    const getters = {
      env(state) {
        return state.env
      },
      buildEnv(state) {
        return state.buildEnv
      },
    }
    
    export default {
      state,
      mutations,
      actions,
      getters,
    }
    

    As you can see above, if (process.server) is executed when the app is being rendered server side. This allows you to save anything inside process.env into the Vuex state. Then, when you want to call them in your components just run:

    computed: {
        ...mapGetters(['env', 'buildEnv']),
    }
    

    Inside your component, and voila!

    0 讨论(0)
提交回复
热议问题