首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在使用ts-jest时转换导入

在使用ts-jest时转换导入
EN

Stack Overflow用户
提问于 2021-06-22 00:46:37
回答 1查看 320关注 0票数 0

上下文:我在我的项目中使用了jest、typescript、babel和material-ui。

我一直在调查我们的单元测试的一个性能问题,这个问题似乎是由大多数单元测试导入整个material-ui造成的,因为我们是从@material-ui/core导入它们的。我一直试图用一个巴别塔插件来解决这个问题,不管是使用自定义插件还是babel-plugin-transform-imports包,它似乎也能做我想要的事情。

问题是这个插件似乎从未被调用过。我们使用ts-jest,所以它同时通过babel和typescript编译器。但似乎typescript可能会在babel转换它们之前解决所有的导入。

我已经考虑过只使用babel来完成所有的typescript编译,但随后将jest构建过程与我们使用的主要构建过程分开维护。不管怎样,我现在遇到了让它正常运行的问题。我也在考虑做一个自定义的jest转换器,但它似乎比babel插件更脆弱,更难维护。

Jest配置:

代码语言:javascript
复制
"preset": "ts-jest",
"globals": {
  "ts-jest": {
    "babelConfig": {
        "presets": [
            "@babel/react",
            "@babel/env"
        ],
        "plugins": [
            "@babel/plugin-transform-spread",
            "./customPlugin.js"
        ]
    },
    "isolatedModules": true
  }
},
"testEnvironment": "jsdom",
"collectCoverageFrom": [
  <coverage paths>
],
"setupFiles": [
  <setup files>
],
"moduleFileExtensions": [
  "ts",
  "tsx",
  "js"
],
"moduleNameMapper": {
   <mappers>
},
"coverageDirectory": "./test/coverage",
"testResultsProcessor": "./node_modules/jest-html-reporter",
"transform": {
  "^.+\\.tsx?$": "ts-jest",
  ".+\\.jsx?$": "babel-jest",
  "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileTransformer.js"
},
"testRegex": "/src/.*\\.spec\\.(ts|tsx)$",
"snapshotSerializers": [
  "enzyme-to-json/serializer"
]

我的tsconfig文件:

代码语言:javascript
复制
{
  "compilerOptions": {
    "sourceMap": true,
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "jsx": "react",
    "lib":[ "es2015", "dom" ,"es2017"],
    "target": "es5",
    "resolveJsonModule": true,
    "experimentalDecorators": true,
    "skipLibCheck": true,
    "outDir": "./dist",
    "baseUrl":  ".",
    "paths": {
      <custom paths>
    }
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "**/*.spec.ts",
    "**/*.spec.tsx"
  ]
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-23 23:22:48

看起来我误解了typescript编译器的输出。typescript编译器将我所有的导入语句转换为requires,所以我的寻找ImportDeclaration访问者的babel插件最终什么也没做。

我还发现ts-jest还有一个选项可以在typescript上指定一个ast转换器:https://kulshekhar.github.io/ts-jest/docs/processing/

https://kulshekhar.github.io/ts-jest/docs/getting-started/options/astTransformers

https://levelup.gitconnected.com/writing-typescript-custom-ast-transformer-part-1-7585d6916819

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68071764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档