You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React 18+TypeScript+create-react-app:npm start为何忽略.env.development?

问题描述

使用create-react-app搭建React 18应用,开发工具为Visual Studio Code,在项目根目录放置两个.env文件:

  • .env:REACT_APP_IS_CONSOLELOG=false
  • .env.development:REACT_APP_IS_CONSOLELOG=true

执行npm start启动应用后,终端显示NODE_ENV为development,但在.tsx文件中打印process.env.REACT_APP_IS_CONSOLELOG得到的值是false,未读取到.env.development中的true。已按官方文档安装dotenv,但问题依旧。

项目package.json的依赖及scripts配置如下:

依赖

"dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^27.5.2",
    "@types/node": "^16.11.64",
    "@types/react": "^18.0.21",
    "@types/react-dom": "^18.0.6",
    "dotenv": "^16.0.3",
    "jest-editor-support": "^30.2.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-error-boundary": "^3.1.4",
    "react-query": "^3.39.2",
    "typescript": "^4.8.4",
    "uuid": "^9.0.0",
    "web-vitals": "^2.1.4"
  },

Scripts

"scripts": {
    "start": "set HTTPS=true&&set SSL_CRT_FILE=C:/Users/MyName/Documents/Certificates/cert.crt&&set SSL_KEY_FILE=C:/Users/MyName/Documents/Certificates/cert.key&&react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
解决步骤
  • 卸载手动安装的dotenv:create-react-app的react-scripts已经内置了dotenv处理逻辑,手动安装的dotenv会干扰内置流程。执行命令:
    npm uninstall dotenv
    
  • 检查.env文件格式:确保变量定义没有多余空格,正确格式应为REACT_APP_IS_CONSOLELOG=true,等号两侧不能有空格;同时确认.env.development文件名拼写完全正确,没有写成.env.dev或其他变体。
  • 重启开发服务器:修改.env文件后必须重启npm start,否则服务器不会加载新的环境变量配置。
  • 验证start命令的环境变量设置:Windows下的set命令写法没问题,但可以尝试改用跨平台工具统一配置(可选):
    1. 安装cross-env:
      npm install cross-env --save-dev
      
    2. 修改start脚本:
      "start": "cross-env HTTPS=true SSL_CRT_FILE=C:/Users/MyName/Documents/Certificates/cert.crt SSL_KEY_FILE=C:/Users/MyName/Documents/Certificates/cert.key react-scripts start"
      
  • 排查高优先级.env文件:检查项目根目录是否存在.env.development.local文件,该文件优先级高于.env.development,如果存在会覆盖变量值。
关键原理

create-react-app的环境变量加载优先级从高到低为:
.env.development.local > .env.development > .env.local > .env
在development环境下,.env.development的配置会覆盖.env中的同名变量,前提是上述配置都正确。

内容的提问来源于stack exchange,提问作者Tom Regan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 13:45:30