开玩笑,使用 d3 时出现意外的令牌“导出”

问题描述 投票:0回答:3

我读过许多与我类似的问题,但似乎没有一个能解决我的问题。我正在使用 Vue3、TypeScript、Jest 和 D3 v7。当我尝试

import * as d3 from "d3";
时,我在测试中收到此错误:

({"Object.<anonymous>":
  function(module,exports,require,__dirname,__filename,global,jest)
  {export * from "d3-array";

当我这样导入 d3 时也会出现此错误

import { BaseType, Selection, Transition, select } from "d3";

我尝试更新我的笑话配置的transformIgnorePatterns属性以进行读取,但这也不起作用:

transformIgnorePatterns: [
  "<rootDir>/node_modules/(?!d3-(array))",
]

有人可以向我解释一下我在这里缺少的部分吗?下面还有我的整个

jest.config.js
文件

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-(array))",
  ],
  transform: {
    "^.+\\.ts": "ts-jest",
    "^.+\\.vue$": "vue-jest",
  },
};
vue.js d3.js jestjs vuejs3 ts-jest
3个回答
20
投票

一个快速修复方法是使用已转译的缩小版

d3
版本。直接导入缩小版本:

import * as d3 from 'd3/dist/d3.min'

演示1

或者使用 Jest 配置将

d3
映射到缩小版本:

// jest.config.js
module.exports = {
  moduleNameMapper: {
    '^d3$': '<rootDir>/node_modules/d3/dist/d3.min.js',
  },
}

演示2

如果这不是一个选项,您可以配置 Jest 进行转译

d3
(及其也需要转译的依赖项:
internmap
delaunator
robust-predicates
):

// jest.config.js
module.exports = {
  transformIgnorePatterns: [
    '<rootDir>/node_modules/(?!d3|internmap|delaunator|robust-predicates)'
  ],
}

注意:转译会增加测试运行的大量时间。

演示3


0
投票

按照 Tiep Phan 的回答的提示,我将以下内容添加到我的 package.json 文件中:

"jest": {
    "transformIgnorePatterns": ["/node_modules/(?!d3|d3-array|internmap|delaunator|robust-predicates)"] },

0
投票

我必须这样做才能让 ts-node、ts-jest 和 d3 一起工作

jest.config.mjs

export default {
  testEnvironment: 'node',
  extensionsToTreatAsEsm: ['.ts'], // essential
  transform: {
    '^.+\\.tsx?$': [
      'ts-jest',
      {
        useESM: true, // essential
      },
    ],
  },
};

package.json

{
  "type": "module",
    // ...
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext", // wasn't essential but seemed like a good idea
    "module": "ESNext", // essential
    "moduleResolution": "node", // or "node10"
    "allowSyntheticDefaultImports": true, // essential
    // ...

  }
}

测试命令:

node  --experimental-vm-modules node_modules/.bin/jest
# or node --no-warnings --experimental-vm-modules node_modules/.bin/jest 

运行命令

node --loader ts-node/esm  ./src/index.ts
© www.soinside.com 2019 - 2024. All rights reserved.