【问题标题】:Jest with typescript not allowing to import default exports directlyJest with typescript 不允许直接导入默认导出
【发布时间】:2021-03-03 11:15:47
【问题描述】:

我有一个使用 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"]
}

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

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

【问题讨论】:

    标签: typescript jestjs ts-jest


    【解决方案1】:

    默认情况下,Typescript 会将 esModuleInterop 设置为 false,这需要您作为命名空间导入。

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

    tsconfig.json

    {
      "allowSyntheticDefaultImports": true, // Typing support for this case
      "esModuleInterop": true,
    }
    

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

    【讨论】:

      猜你喜欢
      • 2022-12-07
      • 1970-01-01
      • 2019-04-03
      • 2018-10-14
      • 2020-08-28
      • 2020-04-30
      • 1970-01-01
      • 2022-01-09
      • 2016-06-19
      相关资源
      最近更新 更多