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

Jest + Typescript Unable to Import Library (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__/"]
}

我也为此苦苦挣扎了一段时间。我发现 jest 和“cjs”模块存在一些奇怪的问题。不知道为什么会这样,但经过一些研究后,我发现这个 post () 让我知道我需要做什么。 下面是我的 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"
};