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

Vue3+TypeScript+Jest环境引入D3 v7报Unexpected token 'export'错误如何解决

问题根源

D3 v7及以上版本的全量子包、及其依赖的internmap、delaunator等工具库均采用ES Module规范编写,Jest默认会跳过对node_modules下所有文件的编译转换,未编译的ES Module导出语法无法在Jest默认的CommonJS运行环境中被识别,因此抛出语法错误。你之前的配置仅豁免了d3-array的转换忽略规则,未覆盖所有D3相关依赖,所以配置不生效。

解决方案

你可以按如下步骤调整配置:

  • 修改transformIgnorePatterns配置,覆盖所有D3相关包及其依赖的转换豁免规则,替换原有对应配置段即可:
transformIgnorePatterns: [
  "<rootDir>/node_modules/(?!d3|d3-.*|internmap|delaunator|robust-predicates)"
]

如果你嫌正则匹配的包过多,也可以使用更简单的模块映射方案,直接将d3指向已经编译好的UMD产物,不需要单独转换各个子包,在配置中新增如下字段即可:

moduleNameMapper: {
  "^d3$": "<rootDir>/node_modules/d3/dist/d3.min.js"
}
  • 调整transform规则的匹配精度,补全后缀匹配限制,防止误匹配其他后缀的文件:
transform: {
  "^.+\\.ts$": "ts-jest",
  "^.+\\.vue$": "vue-jest"
}
  • 可选配置:如果你的tsconfig.json中设置的module为ESNext,可新增如下配置适配ESM运行模式:
extensionsToTreatAsEsm: [".ts", ".vue"],
globals: {
  "ts-jest": {
    useESM: true
  }
}

修改后完整配置参考

module.exports = {
  collectCoverageFrom: [
    "**/src/**.ts", 
    "**/src/**/**.ts", 
    "!**/dist/**", 
    "!**/node_modules/**", 
    "!**/public/**"
  ],
  errorOnDeprecated: true,
  preset: "@vue/cli-plugin-unit-jest/presets/typescript",
  testMatch: ["**/*.spec.ts", "!**/node_modules/**"],
  testPathIgnorePatterns: ["<rootDir>/dist/", "<rootDir>/node_modules/"],
  modulePaths: [
    "<rootDir>"
  ],
  transformIgnorePatterns: [
    "<rootDir>/node_modules/(?!d3|d3-.*|internmap|delaunator|robust-predicates)"
  ],
  transform: {
    "^.+\\.ts$": "ts-jest",
    "^.+\\.vue$": "vue-jest",
  },
  // 可选,使用模块映射的话可以保留原有transformIgnorePatterns,新增以下配置
  // moduleNameMapper: {
  //   "^d3$": "<rootDir>/node_modules/d3/dist/d3.min.js"
  // }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:24:02