react v18——env环境变量配置、打包配置(craco)

一、env文件

像其他项目一样,在根目录新建 .env 文件,如 .env.development

env 复制代码
REACT_APP_ENV=development
REACT_APP_API_BASE_URL=http://192.168.2.107:31000

REACT_APP_API_BASE_URL 可以用在 axios 封装的位置,作为 baseURL

js 复制代码
const instance = axios.create({
baseURL: process.env.REACT_APP_API_BASE_URL,
  timeout: 30000,
  // `withCredentials` 表示跨域请求时是否需要使用凭证
  withCredentials: false,
});

这种直接使用 全链接请求 的方式,需要 后端 配合解决下 跨域 问题。

二、代理配置

如果想要用代理,可以 在 craco.config.js 中配置:

(在使用less篇,有 craco的安装使用步骤

js 复制代码
// 跨域配置
  devServer: {
    proxy: {
      "/api": {
        target: "http://192.168.2.107:31000",
        changeOrigin: true,
        pathRewrite: {
          "^/api": "",
        },
      },
    },

这时候 axios 的 baseUrl 就不用全链接了,比如:

js 复制代码
const instance = axios.create({
  baseURL: "/api",
  timeout: 30000,
  // `withCredentials` 表示跨域请求时是否需要使用凭证
  withCredentials: false,
});

三、package.json 打包配置

  • 安装 cross-env:yarn add cross-env
  • 修改scripts,即可使用对应命令打包
json 复制代码
"scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "react-scripts eject",
    "build:dev": "cross-env REACT_APP_ENV=development craco build",
    "build:test": "cross-env REACT_APP_ENV=test craco build",
    "build:prod": "cross-env REACT_APP_ENV=production craco build"
  },
相关推荐
一只小阿乐18 分钟前
TypeScript中的React开发
前端·javascript·typescript·react
Java码农也是农4 小时前
ReAct vs Plan-and-Execute:哪种Agent架构更适合你的场景
react·plan+execute
这是个栗子13 小时前
TypeScript(三)
前端·javascript·typescript·react
最初的↘那颗心1 天前
Prompt高级推理:COT思维链、Self-Consistency与ReAct模式实战
大模型·prompt·react·cot·思维链
起来改bug3 天前
【AiAgent学习】Agent中的ReAct模式
学习·react·aiagent入门
ん贤3 天前
ReAct Agent 与 Agent 编排:从单 Agent 闭环到多 Agent 协作(纯享版)
人工智能·ai·agent·react
sun_tao14 天前
● ReAct vs Plan-and-Execute 详细对比 核心思想
agent·react·plan_execute
月光宝盒造梦师5 天前
Ant Design Ellipsis 中的判断逻辑 isEleEllipsis 方法非常消耗性能
javascript·react·优化
努力不熬夜 ^_^5 天前
我用 GLM-5.1 重构了我的 AI 项目
java·重构·react·glm·vibe coding·coding plan
蜘蛛侠..6 天前
什么是 Plan-and-Execute 模式?与ReAct模式区别?
java·ai·大模型·llm·agent·react·plan模式