Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
Back to tool/Back to issues
#5048·X6

v3.1.7 包的 module 声明与 CJS 产物冲突,导致 Node.js ESM 加载失败

Author: ericfitzCreated Mar 23, 2026Updated May 21, 2026
Labelswaiting for maintainer

问题描述

@antv/[email protected] 的 package.json 声明了 "type": "module",但 lib/ 目录下的产物使用的是 CommonJS 语法(require()、exports)。这导致 Node.js 将 lib/index.js 按 ESM 加载时报错:

ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension
and '@antv/x6/package.json' contains "type": "module".

复现步骤

  1. 安装 @antv/[email protected]
  2. 在 Vitest(pool: forks)或任何使用 Node.js 原生 ESM 加载器的环境中引入:
    typescript
    import { Graph } from '@antv/x6';
  3. 运行测试或脚本,触发报错

根本原因

  • package.json 中 "main": "lib/index.js" 指向 CJS 产物
  • package.json 中 "module": "es/index.js" 指向 ESM 产物
  • package.json 中 "type": "module" 使 Node.js 将所有 .js 文件视为 ESM
  • 但 lib/index.js 实际上是 CJS 代码(使用 Object.defineProperty(exports, ...) 和 require())

此外,es/ 目录下的 ESM 产物也存在问题:使用了裸目录导入(如 import * from './shape',其中 shape 是目录),这违反了 ESM 规范,Node.js 严格模式下不支持目录导入。

建议修复方案

以下任一方案均可:

  1. 移除 "type": "module":让 lib/ 下的 CJS 代码正常工作
  2. 将 lib/ 下的文件扩展名改为 .cjs:明确标识为 CommonJS
  3. 添加 "exports" 字段:通过条件导出分别指定 require 和 import 的入口
  4. 修复 es/ 目录的裸目录导入:补全 index.js 后缀

推荐方案 3(添加 exports 字段),示例:

json
{
  "exports": {
    ".": {
      "import": "./es/index.js",
      "require": "./lib/index.js"
    }
  }
}

同时修复 es/ 中的目录导入问题。

环境信息

  • @antv/x6 版本:3.1.7
  • Node.js 版本:22.22.1
  • 包管理器:pnpm
  • 测试框架:Vitest 4.1.0(pool: forks)
  • 构建工具:Vite(构建正常,仅测试环境受影响)

Source: antvis/X6

View original on GitHubView discussion on GitHub