Skip to content

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

@ericfitz

Description

@ericfitz

问题描述

@antv/x6@3.1.7package.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/x6@3.1.7
  2. 在 Vitest(pool: forks)或任何使用 Node.js 原生 ESM 加载器的环境中引入:
    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" 字段:通过条件导出分别指定 requireimport 的入口
  4. 修复 es/ 目录的裸目录导入:补全 index.js 后缀

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

{
  "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(构建正常,仅测试环境受影响)

Metadata

Metadata

Assignees

No one assigned

    Labels

    waiting for maintainerTriage or intervention needed from a maintainer

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions