【问题标题】:How to use .env in react js如何在反应 js 中使用 .env
【发布时间】:2018-11-04 11:17:24
【问题描述】:

如何在 react 中使用 .env。我可以通过

访问 .env.development 和 .env.production
 "start":"react-scripts start",
 "build": "react-scripts build",

如何访问另一个像 .env.staging ?

我是这样给的

"build_staging": "set REACT_APP_ENV=staging & react-scripts build",

但不工作。

请给点建议。

【问题讨论】:

  • 你使用的是什么操作系统?
  • 我用的是mac,不过windows应该也能用。
  • 我已经添加了一个答案,请查看是否有帮助,如果有帮助,请投票并接受:)

标签: reactjs environment-variables package.json


【解决方案1】:

为了在 linux(我的生产服务器)和 windows(我的开发服务器)之间保持一致,我使用 cross-env

npm install --save 跨环境

我的脚本看起来像这样

"scripts": {
    "dev": "cross-env NODE_ENV=development node server",
    "build": "cross-env NODE_ENV=production next build ",
    "start": "cross-env NODE_ENV=production node server"
  },

所以要设置像 REACT_APP_ENV 这样的自定义环境,您需要

"build_staging": "cross-env REACT_APP_ENV=staging react-scripts build",

您可以使用

在您的 javascript 代码中访问它

process.env.REACT_APP_ENV

还可以启动您可能想要添加的登台服务器

"start_staging": "cross-env REACT_APP_ENV=staging react-scripts start"

更多关于这个here

【讨论】:

  • 即使给出了这个,它也在进行开发 -> "build_staging": "cross-env REACT_APP_ENV=staging react-scripts build",
  • 您可能需要在启动应用程序时添加它,例如 "start": "cross-env REACT_APP_ENV=staging react-scripts start",
  • 是的,您需要添加到启动脚本中,或者最好添加一个新脚本,例如“start_staging”:“cross-env REACT_APP_ENV=staging react-scripts start”,以启动临时服务器。
  • Build_staging 命令不起作用,它仅显示为开发。 start_staging 显示为暂存。
【解决方案2】:

[上下文] - 我用Create React 创建了 React 项目。 - 在 Windows 10 上运行 - 使用 VSCode IDE - 我在/src 文件夹上方有文件.env.development。 - 我的代码有console.log(process.NODE_ENV)console.log(process.REACT_APP_YOUR_KEY)


[问题] 当我使用npm start 运行程序时,浏览器会为NODE_ENV 打印“开发”,但对于我的React .env 变量,它会打印undefined

我尝试运行npm start,并将package.json 的默认脚本更改为start 脚本:set REACT_APP_YOUR_KEY && react-scripts start。然后没有任何undefined,一切正常。 ?


[解决方案] 原因是没有正确检测到文件.env.development。我的假设是环境开发文件,Windows或VSCode检测不好。

Windows File Explorer files

VS Code explorer. Look up the icon of the files ?

您必须将文件名从.env.development 更改为.env

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 2020-04-26
    • 2022-11-02
    • 2022-08-15
    相关资源
    最近更新 更多