首页 > 解决方案 > Jest 无法导入包,而我的其他打字稿代码导入它

问题描述

在 Jest 测试文件中,如果我这样做:

import _ from 'lodash';

然后_评估为undefined

如果,OTOH,我这样做:

import * as _ from 'lodash';

然后_得到评估就好了。

我的问题是这怎么可能,因为在我的 Typescript 代码库的其他部分我正在做import _ from lodash没有任何问题。我在假设 Jest 使用与tsconfig.js我的捆绑器相同的情况下进行操作babel.config.js,那么为什么我会得到这种不同的结果呢?

jest.config.js这里获得了一个非常简单的配置:

module.exports = {
    "roots": [
        "<rootDir>/src"
    ],
    "testMatch": [
        "**/__tests__/**/*.+(ts|tsx|js)",
        "**/?(*.)+(spec|test).+(ts|tsx|js)"
    ],
    "transform": {
        "^.+\\.(ts|tsx)$": "ts-jest"
    },
}

这是我的babel.config.js

module.exports = {
        "presets": ["@babel/preset-env", "@babel/react"],
        "compact" : false,
    "plugins": [
            "@babel/plugin-proposal-class-properties"
        ]
}

最后我tsconfig.json的是:

{
  "compilerOptions": {
    "strict": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "forceConsistentCasingInFileNames": true,        
    "outDir": "./dist/",
    "sourceMap": true,
    "module": "es6",
    "target": "es5",
    "jsx": "react",
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "moduleResolution": "node",
    "baseUrl": ".",
    "paths": {
        "*": [
            "node_modules/*",
            "src/typings/*",
            "node_modules/@siedlerchr/types-ol-ext/@types/*"
        ]
    },
    "resolveJsonModule": true
  }
}

标签: typescriptwebpackjestjsbabeljs

解决方案


推荐阅读