我的 React 应用程序正在使用 .env 文件中的值而不是 .env.local 文件

问题描述

dotenv 模块 should be 将我的 .env.local 文件优先于我的 .env 文件,但事实并非如此。当我在两个文件中都设置了 REACT_APP_API_BASE 时,应用程序始终使用 .env 中的值。如果我删除 .env.local 中的匹配定义,它仅使用 .env 中的值。


.env

REACT_APP_API_BASE = 'https://api-staging.mysite.com/api'

.env.local

REACT_APP_API_BASE = 'https://api-qa.mysite.com/api'

该应用正在对 https://api-staging.mysite.com/api/endpoint.

进行 API 调用

我做错了什么?

作为参考,我没有直接运行 react-scripts,我使用的是 CRACO。

package.json

  "scripts": {
    "start": "craco start","build": "craco build"
  },"dependencies": {
    "@craco/craco": "^6.0.0","@material-ui/core": "^4.11.2","@material-ui/icons": "^4.11.2","@material-ui/lab": "^4.0.0-alpha.57","@sentry/react": "^6.2.2","@sentry/tracing": "^6.2.2","@sentry/webpack-plugin": "^1.14.0","@stripe/react-stripe-js": "^1.3.0","@stripe/stripe-js": "^1.13.0","mixpanel-browser": "^2.41.0","react": "^16.6.0","react-dom": "^16.0.0","react-gtm-module": "^2.0.11","react-intl": "^5.10.14","react-router-dom": "^5.2.0","react-scripts": "4.0.1","typescript": "^4.1.3","universal-cookie": "^4.0.4","web-vitals": "^0.2.4"
  },"devDependencies": {
    "@formatjs/cli": "^3.0.1","@storybook/addon-a11y": "^6.1.20","@storybook/addon-actions": "^6.1.20","@storybook/addon-essentials": "^6.1.20","@storybook/addon-links": "^6.1.20","@storybook/components": "^6.1.20","@storybook/node-logger": "^6.1.20","@storybook/preset-create-react-app": "^3.1.5","@storybook/react": "^6.1.18","@testing-library/jest-dom": "^5.11.9","@testing-library/react": "^11.2.5","@testing-library/user-event": "^12.8.3","@types/jest": "^26.0.20","@types/mixpanel-browser": "^2.35.6","@types/node": "^14.14.20","@types/react": "^17.0.0","@types/react-dom": "^17.0.0","@types/react-gtm-module": "^2.0.0","@types/react-router-dom": "^5.1.7","babel-plugin-formatjs": "^9.0.1","babel-plugin-import": "^1.13.3","dotenv-webpack": "^1.8.0","eslint-plugin-sonarjs": "^0.5.0","hint": "^6.1.1","jest-chain": "^1.1.5","react-test-renderer": "^17.0.1"
  },"babel": {
    "presets": [
      "react-app"
    ],"plugins": [
      [
        "formatjs",{
          "idInterpolationPattern": "[sha512:contenthash:base64:6]","ast": true
        }
      ]
    ]
  },

解决方法

发布赏金五分钟后,我终于弄明白了......

我的一个文件顶部有 require('dotenv').config();。显然,这是用主 .env 文件中的任何内容覆盖了 CRA 找到的配置。一旦我从我的代码中删除该行,一切正常。