如何在React JS中设置环境变量?

24

我是React JS的新手。我正在尝试从React应用程序构建war文件,但在下面的某个地方遇到了问题。它给了我以下错误。

Creating an optimized production build...

Treating warnings as errors because process.env.CI = true.
Most CI servers set it automatically.

Failed to compile.



./src/Home.js
  Line 2:   'AppNavbar' is defined but never used  no-unused-vars
  Line 3:  'Link' is defined but never used       no-unused-vars
  Line 4:  'Button' is defined but never used     no-unused-vars
  Line 4:  'Container' is defined but never used  no-unused-vars

./src/App.js
  Line 5:   'MenuBar' is defined but never used        no-unused-vars
  Line 6:   'PrivilegeList' is defined but never used  no-unused-vars
  Line 8:   'logo' is defined but never used           no-unused-vars


  npm ERR! code ELIFECYCLE
  npm ERR! errno 1
  npm ERR! my-app@0.1.0 build: `react-scripts build`
  npm ERR! Exit status 1
  npm ERR!
  npm ERR! Failed at the my-app@0.1.0 build script.
  npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

  npm ERR! A complete log of this run can be found in:
    npm ERR!     D:\ReactJS-workspace\my-app\npm\cache\_logs\2018-10-19T07_44_19_233Z-debug.log
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 01:36 min
    [INFO] Finished at: 2018-10-19T13:14:19+05:30
    [INFO] ------------------------------------------------------------------------
    [ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.3.2:exec (npm run build (compile)) on project my-app: Command execution failed.: Process exited with an error: 1 (Exit value: 1) -> [Help 1]
    [ERROR]
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR]
    [ERROR] For more information about the errors and possible solutions, please read the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

以下是我的文件夹结构。

enter image description here

我想设置process.env.CI = false,如何在React JS中设置环境变量?


我认为你只需要禁用执行eslint或jshint步骤的任务即可实现这一点。 - Ashvin777
CI正在执行哪个脚本?你能分享一下这个脚本吗? - Ashvin777
2
最简单的修复方法是删除未使用的导入。 - Code-Apprentice
@Code-Apprentice 是的,我移除了未使用的导入,它修复了错误,谢谢。 - Developer Desk
只需简单地运行 CI=false npm run build,无需进行任何更改。 - Kid
12个回答

22

要在当前进程执行中设置它,只需编辑您的package.json文件,并将“build”脚本修改如下:

"scripts": {
"start": "react-scripts start",
"build": "set \"CI=false\" && react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject" }

这将把CI环境变量设置为“false”。现在,您可以使用设置了CI变量的命令执行构建命令:

npm run build

1
对我没用,我正在使用Travis CI,它向我显示“将警告视为错误,因为process.env.CI = true。大多数CI服务器会自动设置它。” - Ashish Kamble
@AshishKamble,你找到解决方案了吗? - Teddy Kossoko
@TeddyKossoko 不好意思,实际上不是这样的。 - Ashish Kamble
@AshishKamble 请尝试使用 CI=false npm run build - Kid

14

请查看这个包dotenv

  1. 在您的工作目录中创建一个新文件.env

  2. 通过运行npm install dotenv安装dotenv

  3. require('dotenv').config()添加到您的应用程序中

  4. 在该文件中写入process.env.CI = false

  5. [如果使用git] 将.env添加到您的.gitignore

  6. 重启您的应用程序

或者运行CI=false npm run build


我需要在每个JS文件中添加require('dotenv').config()吗? - Developer Desk
你的意思是说 App.js 对吧...!还有在 #misc 部分的第五点我应该添加 .env 吗? - Developer Desk
是的,App.js,第五点是如果你正在使用git,否则请忽略它。 - Atishay Jain
仍然出现相同的错误,没有解决上述错误。 - Developer Desk
运行一次 CI=false npm run build - Atishay Jain
如果这些环境变量是可访问的,那么它们能否在index.html文件中被访问?如果可以,那么我该如何访问它们并在脚本标签中执行一些代码?请回复我。 - Siluveru Kiran Kumar

10

您的问题标题与描述中所发生的情况非常不同。

在React中使用环境变量时,它们必须以REACT_APP_作为前缀。

例如,以下内容将被React应用程序检测到:

REACT_APP_API_URL=/api

而这个则不会:

API_URL=/api

更多信息请参阅官方文档:


7
您可以在.env文件中设置环境变量。
以下是步骤:
  1. 在项目根目录下创建名为.env的文件。
  2. 现在,当您要添加变量时,必须添加前缀REACT_APP。例如:如果您想要添加API的API_URL变量,则必须按以下方式添加带有前缀RECT_APP的变量:
  3. REACT_APP_API_URL

  4. 停止运行服务器并使用npm start重新启动。
  5. 要访问环境变量,您必须调用如下: process.env.REACT_APP_API_URL
现在您可以访问环境变量了。
提醒:
  1. 请确保已添加前缀(REACT_APP)。
  2. 请停止服务器并重新启动,以便加载已添加的环境变量。

良好的细节和逐步指南。重点在于第3点:您必须停止服务器并重新启动它!这解决了我的问题。 - G M

3
"scripts": {
    "start": "react-scripts start",
    "build": "CI=false react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"  
  },

尝试这样做...这将把CI设置为false。

我在使用React和Azure Static Web App CI/CD时遇到了类似的问题,通过 "build": "CI=false react-scripts build" 解决了它,现在部署已完成 :) - EduardoUstarez

2

您需要在根目录中创建.env文件,并在该文件中定义变量。请确保每个变量都以REACT_APP_开头,例如:REACT_APP_IS_PROD=1

每次更改或创建新的变量时,您需要重新启动服务器。

参考


1
创建一个.env文件,或者.env.dev,.env.qa,.env.stg ...等等。
在该文件中添加以下行。
CI=false

如果您还没有安装 env-cmd,请先安装它并将其包含在 package.json 中。然后,在 package.json 的 "scripts" 中添加以下行。
  "scripts": {
    "start": "env-cmd -f .env.dev react-scripts start",
    "build": "react-scripts build",
    "build:dev": "env-cmd -f .env.dev npm run-script build",
    "build:qa": "env-cmd -f .env.qa npm run-script build",
    "build:stg": "env-cmd -f .env.stg npm run-script build",
    "build:prod": "env-cmd -f .env.prod npm run-script build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

然后使用“npm run build:dev”构建,或相应地使用命令进行构建。

1

对于Windows:

设置REACT_APP_ENV=development && react-scripts start

对于Linux、Ubuntu和macOS:

REACT_APP_ENV=development react-scripts start


0

Github Actions

你想使用Github Actions构建和上传网站吗?

也许你想在Github repo中创建一个文件\.github\workflows\deploy.yaml,并添加类似以下内容的代码。

name: Upload Website

on:
  push:
    branches:
      - main

jobs:
  deploy:
    name: Upload Website - deploy
    runs-on: ubuntu-latest

    steps:
      - name: Checkout source code
        uses: actions/checkout@master

      - name: Load AWS credentials from Github Secrets
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: ${{ secrets.AWS_REGION }}

      - name: Load dependencies (node_modules)
        run: yarn

      - name: Build site
        run: yarn build
        env:
          CI: false

      - name: Copy files to S3
        run: |
          aws s3 sync ./build s3://my-s3-website-bucket --delete --exclude "*.map" --acl public-read

      - name: Clear Cloudfront cache
        run: |
          aws cloudfront create-invalidation --distribution-id ${{ secrets.CF_DIST_ID }}--paths "/*"

参考资料:


0

我是通过搜索与Bitbucket Pipelines的集成相关的问题而来到这里的。

对于其他人寻找相同答案的人,您可以在您的存储库下的设置/存储库变量中添加CIfalse(如果您不希望它成为您版本控制的代码的一部分)。

如果您想要将其添加到您Bitbucket中的所有存储库中,则应该在全局设置中添加,但最好逐个存储库添加。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接