Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
162 views
Welcome To Ask or Share your Answers For Others

1 Answer

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'
  ])
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...