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

React+TypeScript项目出现ReferenceError: require is not defined报错求助

解决React + TypeScript中"ReferenceError: require is not defined"的问题

Hey there! Let's break down why you're hitting this error and how to fix it properly.

为什么会出现这个错误?

你用create-react-app创建的是前端浏览器应用,但你写的代码里用了require('fs')和fs.writeFileSync——这些都是Node.js环境特有的API,浏览器根本不支持:

  • require是Node.js的模块加载语法,浏览器没有这个全局变量,所以会抛出ReferenceError。
  • 更重要的是,浏览器出于安全限制,不允许前端代码直接读写本地文件系统,哪怕你能调用fs模块,也会被浏览器阻止。

针对你的需求,有两种解决方案

你要写入JSON文件,大概率是两种场景之一,对应不同的解决方式:

场景1:让用户下载生成的JSON文件(前端实现)

如果是想把数据导出给用户本地保存,可以通过创建Blob对象生成下载链接,让用户手动保存。这是前端能做到的安全方式:

// 在你的React组件中添加这个函数
const saveJsonToLocal = () => {
  // 注意:这里的this.Array要换成你实际的数组变量,比如this.state.tracks或者组件内的state/prop
  const dataToSave = { tracks: this.Array };
  const jsonString = JSON.stringify(dataToSave, null, 2);
  const blob = new Blob([jsonString], { type: 'application/json' });
  const downloadUrl = URL.createObjectURL(blob);
  
  // 创建临时a标签触发下载
  const link = document.createElement('a');
  link.href = downloadUrl;
  link.download = 'file.json'; // 下载后的文件名
  document.body.appendChild(link);
  link.click();
  
  // 清理临时资源
  document.body.removeChild(link);
  URL.revokeObjectURL(downloadUrl);
};

调用这个函数,浏览器就会自动下载生成的file.json文件。

场景2:把数据保存到服务器的文件中(需要后端配合)

如果是想把数据写入服务器端的文件,你需要搭建一个简单的后端服务(比如用Node.js + Express),前端把数据发送给后端,由后端来完成文件写入:

后端代码(Node.js + Express)

const express = require('express');
const fs = require('fs');
const cors = require('cors'); // 解决跨域问题
const app = express();

app.use(cors());
app.use(express.json()); // 解析JSON请求体

// 接收前端数据的接口
app.post('/save-data', (req, res) => {
  try {
    const jsonData = JSON.stringify(req.body, null, 2);
    fs.writeFileSync('./file.json', jsonData);
    res.status(200).send('数据已成功保存到服务器');
  } catch (error) {
    res.status(500).send('保存数据失败:' + error.message);
  }
});

app.listen(3001, () => {
  console.log('后端服务运行在 http://localhost:3001');
});

前端代码(React + TypeScript)

const sendDataToServer = async () => {
  const dataToSave = { tracks: this.Array };
  try {
    await fetch('http://localhost:3001/save-data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(dataToSave),
    });
    alert('数据已保存到服务器!');
  } catch (error) {
    console.error('保存失败:', error);
    alert('保存数据时出错,请检查后端服务是否运行');
  }
};

额外小提醒

  • 注意你的代码里this.Array可能是个笔误,应该替换成你实际要保存的数组变量,比如组件state里的tracks数组。
  • 前端环境和Node.js后端环境是完全独立的,不要在React组件里使用Node.js的API,这是新手很容易踩的坑~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 07:13:12