【已解决】vue/react .env.development 中读取不到变量:undefined


一、问题

react 项目中,通过 ·process.env..env.env.development 中读取不到变量,undefined

二、解决

  • 首先,确保 .env.env.development 文件放在项目根目录(和 package.json 同级),而不是 src 目录
  • 其次,必须以 REACT_APP_ 开头建立自定义环境变量(同理,vue项目是以 VUE_APP_ 开头)
    • bad:API_URL=http://localhost:8080
    • good:REACT_APP_API_URL=http://localhost:8080
  • build 读取 .env 中变量
  • start 读取 .env.development 中变量

三、拓展学习

Adding Custom Environment Variables | Create React App

  • What other .env files can be used?

Note: this feature is available with [email protected] and higher.

.env:Default.
.env.local:Local overrides. This file is loaded for all environments except test.
.env.development, .env.test, .env.production:Environment-specific settings.
.env.development.local, .env.test.local, .env.production.local:Local overrides of environment-specific settings.

  • Files on the left have more priority than files on the right:

npm start: .env.development.local, .env.local, .env.development, .env
npm run build: .env.production.local, .env.local, .env.production, .env
npm test: .env.test.local, .env.test, .env (note .env.local is missing)

These variables will act as the defaults if the machine does not explicitly set them.


猜你喜欢

转载自blog.csdn.net/qq_32682301/article/details/129277342
今日推荐