1. 在项目根目录下新建一个文件 '.env.development',将需要的环境变量写入该文件,如:
NODE_ENV=development
API_URL='http://localhost:3000/api'
  1. 在 'package.json' 文件中添加 scripts,如:
"scripts": {
  "start": "react-scripts start",
  "start:dev": "cp .env.development .env && react-scripts start",
  "start:prod": "cp .env.production .env && react-scripts start",
  "build": "react-scripts build",
  "build:prod": "cp .env.production .env && react-scripts build"
}

其中,'start:dev' 和 'start:prod' 分别是启动开发环境和生产环境的命令,'build:prod' 是打包生产环境的命令。

  1. 在命令行中运行命令 'npm run start:dev' 或 'npm run start:prod' 即可启动对应的环境。
React 项目本地环境切换:.env.development 和 .env.production 使用指南

原文地址: https://www.cveoy.top/t/topic/oCxQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录