typescript - Jest with typescript 不允许直接导入默认导出
问题描述
我有一个使用 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'
但我想使用标准的 ES6 导入方式,import React from 'react'
而不是 typescript 方式。
解决方案
默认情况下,Typescript 将设置esModuleInterop
为false
需要您作为命名空间导入。
您可以将其更改true
为能够在没有您想要的命名空间的情况下导入:
tsconfig.json
{
"allowSyntheticDefaultImports": true, // Typing support for this case
"esModuleInterop": true,
}
注意:在您进行配置时,您可能必须使用选项运行jest --no-cache
以防止缓存。
推荐阅读
- python - 通过 python 使用 Windows 10 系统用户输入提示
- python - 使用 python 并行化在图上进行大处理
- sql - 为什么我在 SQL 中返回此语法错误?
- vue.js - b-dropdown-item-button 太长,如何缩短或换行?
- javascript - 谷歌分析 onClick 事件不起作用
- postgresql-9.5 - PostgreSQL 9.5.15 - 左连接与巨大的表需要时间
- ios - 如何将 Autodesk Forge Viewer 嵌入移动应用程序?
- sql - 从表中排除一组数据
- python - Bottle POST 方法 - 获取查询参数
- javascript - ES6 映射是如何在底层实现的?