最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Pass or use process.env variable from node to reactjs - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question asked Apr 21, 2016 at 6:03 indexindex 3,7277 gold badges40 silver badges56 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

I found this: http://dev.topheman./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.

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'
  ])
]
发布评论

评论列表(0)

  1. 暂无评论