在 TS 项目中导入纯 ESM 模块未通过 Jest 测试并出现导入错误

cyb*_*bat 10 typescript jestjs es6-modules ts-jest

尝试在 TS 项目中使用纯 ESM 的文件类型模块,但我的笑话失败了。我已按照此处所示设置 ESM 选项,但仍然出现SyntaxError: Cannot use import statement outside a module错误。

我这里做了一个沙箱。

我的代码摘要:

import { fileTypeFromBuffer } from "file-type";
Run Code Online (Sandbox Code Playgroud)

笑话配置:

export default {
  testEnvironment: "jest-environment-node",
  globals: {
    extensionsToTreatAsEsm: [".ts"],
    "ts-jest": {
      useESM: true,
    },
  },
  transform: {
    "^.+\\.(ts|tsx|js|jsx)?$": "ts-jest",
    //"^.+\\.tsx?$": "ts-jest",
  },
  moduleNameMapper: {
    "^(\\.{1,2}/.*)\\.js$": "$1",
  },
  preset: "ts-jest",
  //preset: 'ts-jest/presets/default-esm' // or other ESM presets
};

Run Code Online (Sandbox Code Playgroud)

TS配置:

{
  "extends": "@tsconfig/node14/tsconfig.json",
  "compilerOptions": {
    "target": "ES2018",
    "module": "commonjs",
    "lib": ["es2018"],
    "declaration": true,
    "strict": true,
    "strictNullChecks": true,
    "alwaysStrict": true,
    //importsNotUsedAsValues
    // "noImplicitAny": false,
    "noImplicitReturns": false,
    "noImplicitThis": false,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "noEmit": true,
    "noFallthroughCasesInSwitch": false,
    "inlineSourceMap": true,
    "inlineSources": true,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false,
    // "typeRoots": ["./node_modules/@types"]
    "resolveJsonModule": true,
    "outDir": "dist",
    "baseUrl": ".",

    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Twi*_*her 4

您必须告诉 Jest 使用该选项转换那些 ESM 捆绑库transformIgnorePatterns

此选项指定忽略的路径,默认情况下["/node_modules/", "\\.pnp\\.[^\\\/]+$"]解释了为什么库没有被转换。

最直接的解决方案是设置一个空数组:

transformIgnorePatterns: []
Run Code Online (Sandbox Code Playgroud)

但是您也可以设置更细粒度的配置来排除除某些特定库之外的所有内容,例如文档的正则表达式示例。

另外,"allowJs": true在 TypeScript 配置中添加该选项。