当前位置: 首页 > news >正文

【大前端】React配置配置 开发(development)、生产(production)、测试(test)环境

在 React 项目中配置 开发(development)、生产(production)、测试(test)环境,一般有两种常见方案:

  1. 使用环境变量(推荐,React 官方支持)
  2. 使用多配置文件(如 webpack/vite 配置区分)

梳理一份完整的实践方案 👇


1. 使用 .env 环境变量文件(推荐)

React(使用 Create React App 或 Vite)天然支持环境变量文件。

(1)创建环境变量文件

在项目根目录下新建以下文件:

.env.development   # 开发环境
.env.production    # 生产环境
.env.test          # 测试环境

(2)环境变量命名规范

React 要求自定义环境变量必须以 REACT_APP_ 开头,例如:

# .env.development
REACT_APP_API_URL=http://localhost:3000/api
REACT_APP_DEBUG=true# .env.production
REACT_APP_API_URL=https://api.example.com
REACT_APP_DEBUG=false# .env.test
REACT_APP_API_URL=http://test.api.example.com
REACT_APP_DEBUG=true

(3)在代码中使用

console.log(process.env.REACT_APP_API_URL);
console.log(process.env.REACT_APP_DEBUG);

(4)自动区分环境

  • npm start → 加载 .env.development
  • npm run build → 加载 .env.production
  • npm test → 加载 .env.test

如果你用 Vite,规则类似,只是必须以 VITE_ 开头:

VITE_API_URL=https://api.example.com

2. 使用 webpack/vite 配置文件区分(高级方式)

(1)webpack 方式

webpack.config.js 中使用 DefinePlugin 注入环境变量:

const webpack = require('webpack');module.exports = (env) => ({plugins: [new webpack.DefinePlugin({'process.env.API_URL': JSON.stringify(env.API_URL),}),],
});

运行时指定环境:

webpack --env API_URL=https://api.example.com

(2)Vite 方式

vite.config.js 中使用 define

import { defineConfig } from 'vite';export default defineConfig({define: {__API_URL__: JSON.stringify(process.env.VITE_API_URL),},
});

在代码中直接使用:

console.log(__API_URL__);

3. 结合配置文件方式(适合大型项目)

如果环境变量太多,可以抽象成配置文件:

📂 src/config/index.js

const env = process.env.NODE_ENV; // development | production | testconst configs = {development: {apiBaseUrl: process.env.REACT_APP_API_URL,debug: true,},production: {apiBaseUrl: process.env.REACT_APP_API_URL,debug: false,},test: {apiBaseUrl: process.env.REACT_APP_API_URL,debug: true,},
};export default configs[env];

使用时:

import config from './config';fetch(`${config.apiBaseUrl}/users`).then(res => res.json()).then(data => console.log(data));

总结

  • 小型项目:用 .env.* 文件就够了,官方推荐。
  • 中大型项目.env.* + 配置文件组合,管理更清晰。
  • 自定义构建工具:用 webpack/vite 的 DefinePlugin/define 来注入。

写一个 React 项目完整 demo,里面包含

  1. 环境变量配置.env.development / .env.production / .env.test
  2. 统一的 config 文件管理
  3. 示例 API 请求

适合直接拷贝到 React 项目里使用。


1. 新建环境变量文件

在项目根目录新建以下文件:

.env.development

REACT_APP_API_URL=http://localhost:3000/api
REACT_APP_DEBUG=true

.env.production

REACT_APP_API_URL=https://api.example.com
REACT_APP_DEBUG=false

.env.test

REACT_APP_API_URL=http://test.api.example.com
REACT_APP_DEBUG=true

2. 新建配置管理文件

📂 src/config/index.js

const env = process.env.NODE_ENV; // development | production | testconst configs = {development: {apiBaseUrl: process.env.REACT_APP_API_URL,debug: process.env.REACT_APP_DEBUG === 'true',},production: {apiBaseUrl: process.env.REACT_APP_API_URL,debug: process.env.REACT_APP_DEBUG === 'true',},test: {apiBaseUrl: process.env.REACT_APP_API_URL,debug: process.env.REACT_APP_DEBUG === 'true',},
};export default configs[env];

3. 示例 API 工具类

📂 src/utils/api.js

import config from '../config';export async function fetchUsers() {try {const response = await fetch(`${config.apiBaseUrl}/users`);if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return await response.json();} catch (error) {if (config.debug) {console.error('API Error:', error);}throw error;}
}

4. 在组件中使用

📂 src/App.js

import React, { useEffect, useState } from 'react';
import { fetchUsers } from './utils/api';
import config from './config';function App() {const [users, setUsers] = useState([]);useEffect(() => {fetchUsers().then(setUsers).catch(err => {console.error('加载用户失败', err);});}, []);return (<div><h1>React 多环境配置 Demo</h1><p>当前环境: {process.env.NODE_ENV}</p><p>API 地址: {config.apiBaseUrl}</p><ul>{users.map(user => (<li key={user.id}>{user.name} ({user.email})</li>))}</ul></div>);
}export default App;

5. 启动方式

# 开发环境
npm start   # 自动读取 .env.development# 生产环境(打包)
npm run build   # 自动读取 .env.production# 测试环境
npm test   # 自动读取 .env.test

✅ 这样就有了:

  • 三套环境配置(dev/prod/test)
  • 统一的 config 文件(方便管理)
  • 真实 API 调用 demo

http://www.dtcms.com/a/359324.html

相关文章:

  • C语言强化训练(1)
  • VSCode中使用Markdown
  • 学习笔记:MySQL(day1)
  • 机器学习基础-day01-机器学习介绍
  • 微信小程序开发教程(六)
  • 07.《交换机三层功能、单臂路由与端口安全基础知识》
  • cosy-3
  • 在Ubuntu服务器上安装KingbaseES V009R002C012(Orable兼容版)数据库过程详细记录
  • 服务器音频查找
  • 《打破 “慢“ 的黑箱:前端请求全链路耗时统计方案》
  • 技术框架之RPC
  • 将基于 Spring Boot 3.0.0 的 JavaWeb 应用部署到腾讯云并配置域名
  • codecombat(Ubuntu环境详细docker部署教程)
  • 8.1【Q】VMware相关
  • 【PS实战】逐步打造静物的艺术色调(大学作业)
  • Quantitative Trading
  • python---封装
  • 2025年- H103-Lc211--3090. 每个字符最多出现两次的最长子字符串(双指针)--Java版
  • 基于FPGA的正弦波和及滤波(已通过仿真和上板)
  • Spring boot注解介绍
  • 【51单片机】【protues仿真】基于51单片机音乐盒(8首歌曲)系统
  • 策略模式:灵活应对算法动态切换
  • AI军团协同作战:Manus Wide Research深度解析
  • 【LeetCode_27】移除元素
  • stm32F4挂载emmc以及重定义printf
  • 解决Docker运行hello-world镜像报错问题
  • Decoder 解码器
  • 【MLLM】多模态理解Ovis2.5模型和训练流程(更新中)
  • 工业产品营销:概念、原理、流程与实践指南
  • Ubuntu中通过SSH克隆Windows的远程Git仓库(局域网中挺有用)