【问题标题】:Importing pure ESM module in TS project fails Jest test with import error在 TS 项目中导入纯 ESM 模块未通过 Jest 测试并出现导入错误
【发布时间】:2022-01-16 09:02:49
【问题描述】:

尝试在 TS 项目中使用纯 ESM 的 file-type 模块,但我的玩笑失败了。我已经按照here 的指示设置了 ESM 选项,但仍然收到 SyntaxError: Cannot use import statement outside a module 错误。

我已经做了一个沙盒here

我的代码总结:

import { fileTypeFromBuffer } from "file-type";

笑话配置:

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
};

TSConfig:

{
  "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
  }
}

有什么想法吗?

【问题讨论】:

    标签: typescript jestjs es6-modules ts-jest


    【解决方案1】:

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

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

    最直接的解决办法是设置一个空数组:

    transformIgnorePatterns: []
    

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

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

    【讨论】:

    • 快到了。现在我收到一个错误,即无法找到file-type 所需的包,即使我在 node_modules 中看到它也是如此。 Cannot find module 'strtok3/core' from node_modules/file-type/core.js
    • 这可能与file-type 中的一个错误有关。 strtok3 存在但 strtok3/core 不存在,正确的导入似乎是 strtok3/lib/core 就像本期报道的那样:github.com/sindresorhus/file-type/pull/513
    • 哦,好的,我知道了,我认为是ts-jest 没有在strtok3 中考虑此配置package.json"exports": { "./core": "./lib/core.js" },
    • 你认为这是一个 ts-jest 的错误,然后报告?
    • 老实说,我还没有深入研究以确定这是错误还是配置选项,但我怀疑它尚不支持,因为 ECMAScript 模块支持是实验性的
    猜你喜欢
    • 2021-11-23
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    相关资源
    最近更新 更多