将 process.env 变量从 node 传递或使用到 reactjs [英] Pass or use process.env variable from node to reactjs

查看:23
本文介绍了将 process.env 变量从 node 传递或使用到 reactjs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 process.env 变量从 node 传递或使用到 reactjs?例如我有这个

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'.

但是当我们将它推送到我们的临时服务器并设置 NODE_ENV 变量时,它只在第一次加载时起作用,但随后就不起作用了.我想我确实得到了这个,因为起初它由节点提供服务并且它可以访问服务器变量,但之后它将是 reactjs 服务页面(对吗?)并且它无法访问服务器内容.那么如何在不对其进行硬编码的情况下获得 reactjs 的变量(因为我们最终会有不同的生产集)?

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)?

编辑.如果有差异,我们也会使用 webpack.

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

推荐答案

我发现了这个: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.

这篇关于将 process.env 变量从 node 传递或使用到 reactjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆