问题排查

发布于 2026-08-31

Top-level await is currently not supported with the CJS output format

Top-level await is currently not supported with the CJS output format。

遇到错误:ERROR: Top-level await is currently not supported with the "cjs" output format。

什么是 Top-level await?

// moudle 顶层
 
const result = await readFile(...);

这里面的 await 不在任何函数中,就是 Top-level await。

原因

Top-level await 是 ESM 模块体系支持的能力。

如果脚本按照 CJS 模块体系执行,就会出现错误。

代码
│
│ 使用 Top-level await
▼
需要支持这种语法的模块环境
│
│
× 当前按 CJS 输出
│
▼
报错

解决

改变代码结构,让 await 从模块顶层移动到 async function 内部,从而绕开 CJS 不支持 top-level await 这个问题。

改为:

async function main() {
  const result = await readFile(...);
}
 
main();

即:

Module 顶层
│
├── 定义 async function main()
│       │
│       └── await foo()
│
└── main()

await 已经进入 async function 中,不再是 Top-level await。

JavaScript 的规则不要求当前模块必须依靠 ESM 的 top-level await 能力。

补充

JavaScript 历史上长期没有标准化模块系统,Node.js 使用了 CommonJS。

const fs = require("fs");
 
module.exports = {
  foo
};

简称:CommonJS,CJS。

后来 JavaScript 标准自身定义了模块系统:ECMAScript Modules,简称:ES Modules,ESM,如下:

import fs from "node:fs";
 
export function foo() {}
CommonJSESM
简称CJSESM
导入require()import
导出module.exportsexport
来源Node.js 传统模块系统ECMAScript 标准
Top-level await❌✅
现代前端生态逐渐减少主流方向