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

NodeJS+Babel项目引入supports-color报ERR_REQUIRE_ESM错误如何解决

问题根因

你遇到的报错是因为 supports-color v9及更高版本已经转为纯ESM包,不再支持CommonJS规范的导入方式。你的Babel配置会把源码中的ES Module语法转译为CommonJS的require调用,用require加载纯ESM包就会触发ERR_REQUIRE_ESM错误。

解决方案

方案1:降级supports-color到v8版本(最简便,无额外改动)

v8是supports-color最后一个同时兼容ESM和CommonJS的版本,直接替换版本即可:

npm uninstall supports-color
npm install supports-color@8.x

修改后重新执行npm start即可正常运行,无需调整其他代码或配置。

方案2:保留高版本supports-color,改用动态导入

如果必须使用v9+版本的功能,可以用CommonJS兼容的动态import()语法加载该包,调整你的index.js代码如下:

import express from "express";

const server = express();

// 用动态导入加载ESM包
(async () => {
  const { default: supportsColor } = await import("supports-color");
  if (supportsColor.stdout.has16m) {
    console.log('terminal supports all colors');
  }
})();

server.listen(3000, () => {
  console.log('server is running');
})

调整后重新编译运行即可,不需要修改Babel配置。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:00:04