Jest+Typescript无法导入库(tiny-secp256k1)



我当前正在使用npm包tiny-secp256k1

它提供了许多函数的非默认导出(带有类型声明(。

无论我如何导入它,都要运行我的测试套件。恶作剧投掷:

/pathToProject/node_modules/tiny-secp256k1/lib/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { compare } from "uint8array-tools";
                ^^^^^^
SyntaxError: Cannot use import statement outside a module

我无法判断这个问题是与库隔离的,还是由我的配置引起的。我可以毫不费力地导入其他库。

jest.config.ts

export default {
verbose: true,
transform: {
'^.+\.(ts|tsx)?$': 'ts-jest',
},
testPathIgnorePatterns: ['__tests__/helpers'],
};

tsconfig.json

{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"outDir": "dist",
"allowJs": false,
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
},
"exclude": ["__tests__/"]
}

我也为此挣扎了一段时间。我发现这是一个奇怪的笑话问题;cjs";模块。我不知道为什么会这样,但经过一些研究,我发现这篇文章(Jest不会转换模块-SyntaxError:不能在模块外使用import语句(给了我一个需要做什么的线索。下面是我的jest.config.js文件,它解决了这个问题:

module.exports = {
preset: "ts-jest",
moduleFileExtensions: [
"ts",
"js",
"cjs",
"mjs"
],
transform: {
"^.+\.(ts|tsx)$": "ts-jest",
"node_modules/tiny-secp256k1/lib/cjs/.+\.(js|ts|cjs|mjs)$": "ts-jest",
"node_modules/uint8array-tools/src/cjs.+\.(js|ts|cjs|mjs)$": "ts-jest"
},
moduleNameMapper: {
"^uint8array-tools$": "uint8array-tools/src/cjs",
"^tiny-secp256k1$": "tiny-secp256k1/lib/cjs"
},
transformIgnorePatterns: [
"node_modules/(?!tiny-secp256k1/lib/cjs/.*)",
"node_modules/(?!uint8array-tools/src/cjs/.*)"
],
testMatch: [
"**/test/**/*.test.(ts|js)"
],
testEnvironment: "node"
};

最新更新