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

React构建时执行Node脚本取API数据报错,求替代方案

解决Node脚本ES模块语法冲突问题(无需修改package.json)

你可以通过以下几种方案解决这个问题,完全不需要在项目根目录的package.json中添加"type": "module":

方案1:将脚本后缀改为.mjs

Node会自动识别.mjs后缀的文件为ES模块,直接修改脚本文件名:

  • 把node-script.js重命名为node-script.mjs
  • 运行脚本的命令改为:node src/node-script.mjs
  • 如果要在构建前自动执行,在package.json的scripts中添加:
    "scripts": {
      "prebuild": "node src/node-script.mjs",
      "build": "react-scripts build" // 替换为你的原有构建命令
    }
    

方案2:将脚本转为CommonJS语法

把ES模块的import替换为CommonJS的require,适配Node默认的模块系统:
修改后的脚本代码:

const fetch = require('node-fetch').default; // node-fetch v3+ 需要加.default,v2版本直接使用require('node-fetch')
const fs = require('fs');

fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then((response) => response.json())
    .then((json) => {
        fs.writeFile('./src/data.json', JSON.stringify(json), (err) => {
            if (err) {
                throw new Error('Something went wrong writing the file.')
            }
            console.log('JSON written to file. Contents:', JSON.stringify(json));
        })
    })
  • 保持脚本名为node-script.js,直接用node src/node-script.js运行即可
  • 构建前自动执行的配置:
    "scripts": {
      "prebuild": "node src/node-script.js",
      "build": "react-scripts build"
    }
    

方案3:运行脚本时指定--input-type module参数

通过命令行参数临时指定当前脚本使用ES模块,不影响项目全局配置:

  • 运行脚本的命令改为:node --input-type module src/node-script.js
  • 构建前自动执行的配置:
    "scripts": {
      "prebuild": "node --input-type module src/node-script.js",
      "build": "react-scripts build"
    }
    

额外优化建议

可以把fs.writeFile换成Promise版本的fs.promises.writeFile,避免回调嵌套,代码更简洁:

// ES模块版本,CommonJS版本同理调整导入方式
import fetch from "node-fetch"
import fs from "fs/promises";

async function fetchAndSaveData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    const json = await response.json();
    await fs.writeFile('./src/data.json', JSON.stringify(json));
    console.log('JSON written to file. Contents:', JSON.stringify(json));
  } catch (err) {
    throw new Error(`Failed to fetch or save data: ${err.message}`);
  }
}

fetchAndSaveData();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 17:05:51