Pass or use process.env variable from node to reactjs

一笑奈何 提交于 2020-01-19 11:32:29

问题


How do I pass or use process.env variables from node to reactjs? For example I have this

const nodeEnv = process.env.NODE_ENV || 'development'

in my development and it works (I think because it's development and I DO have a fallback 'development'.

But when we push it to our staging server and set NODE_ENV variable, it only works the first time it loads but subsequently it doesn't. I think I do get this because at first it's served by node and it has access to server variables but afterwards it would be reactjs serving the pages (right?) and it wouldn't have access to server stuff. So how do I get to have variables to reactjs without hardcoding it (because we would eventually have a different set for production)?

EDIT. We also use webpack if that has a difference.


回答1:


I found this: http://dev.topheman.com/make-your-react-production-minified-version-with-webpack/

module.exports = {
  //...
  plugins:[
    new webpack.DefinePlugin({
      'process.env':{
        'NODE_ENV': JSON.stringify('production')
      }
    }),
    // [...]
  ]
  //...
}

In my opinion this is exactly what you are searching for.




回答2:


Webpack also has defined EnvironmentPlugin for this. Just provide an array of environment variable names and they'll be accessible in the client.

plugins: [
  new webpack.EnvironmentPlugin([
    'NODE_ENV',
     'SOME_OTHER_KEY'
  ])
]


来源:https://stackoverflow.com/questions/36760897/pass-or-use-process-env-variable-from-node-to-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!