与打字稿开玩笑不允许直接导入默认导出

Vin*_*lla 2 typescript jestjs ts-jest

我有一个使用 Typescript 编写的 React 应用程序。下面是我在项目中使用的 tsconfig。我能够正确导入默认值,没有任何问题。我所有的文件都有import React from 'react'.

{
  "compilerOptions": {
    "baseUrl": ".",
    "module": "esnext",
    "moduleResolution": "node",
    "outDir": "./dist/",
    "target": "es2016",
    "jsx": "react",
    "allowJs": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "noUnusedLocals": true,
    "types": ["jest"],
    "allowSyntheticDefaultImports": true,
    "paths": {
      "protractor": ["integration-tests/protractor.d.ts"]
    },
  },
  "exclude": [".yarn", "**/node_modules", "dist"],
  "include": ["**/*.js", "**/*.jsx", "**/*.ts", "**/*.tsx", "**/*.json"]
}

Run Code Online (Sandbox Code Playgroud)

但是当我使用 Jest 运行单元测试时,jest 抱怨默认值。因此,Jest 不喜欢默认值并抱怨它是未定义的。我正在使用 ts-jest 进行转换。我开玩笑时是否缺少一个配置来检测正常 es6 方式的默认值?

需要明确的是,我可以像这样导入,import * as React from 'react'但我想使用标准 ES6 导入方式,而import React from 'react'不是打字稿方式。

tmh*_*005 5

默认情况下,Typescript 将设置esModuleInteropfalse需要您导入为命名空间。

您可以将其更改为true能够在没有您想要的名称空间的情况下导入:

tsconfig.json

{
  "allowSyntheticDefaultImports": true, // Typing support for this case
  "esModuleInterop": true,
}
Run Code Online (Sandbox Code Playgroud)

jest --no-cache注意:在进行配置时,您可能必须使用选项来运行以防止缓存。