【问题标题】:How to set up Jest w/ESM to recognize non-cjs modules in node_modules如何设置 Jest w/ESM 以识别 node_modules 中的非 cjs 模块
【发布时间】:2022-08-09 12:04:32
【问题描述】:

已成功设置 jest/esm,但偶尔会发布一个模块,该模块在其 package.json 中同时指定 main 密钥(用于 commonjs)和 module 密钥(用于 ESM)。这会导致开玩笑的错误,例如uuid module

/repo/path/node_modules/uuid/dist/esm-browser/index.js:1
({\"Object.<anonymous>\":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from \'./v1.js\';
                                                                                      ^^^^^^
SyntaxError: Unexpected token \'export\'

我可以看到dist/esm-browser/index.jspackage.json中的module键指定的文件。

如何配置 Jest w/ESM 来处理这些情况,其中 node_modules 中的东西是 ESM?

笑话配置:

{
    \"resetMocks\": true,
    \"testEnvironment\": \"jsdom\",
    \"testMatch\": [
      \"**/src/**/*.(spec|test).[tj]s?(x)\"
    ],
    \"preset\": \"ts-jest/presets/default-esm\",
    \"extensionsToTreatAsEsm\": [
      \".ts\",
      \".tsx\"
    ],
    \"globals\": {
      \"ts-jest\": {
        \"useESM\": true
      }
    },
    \"globalSetup\": \"<rootDir>/jest/setup.cjs\",
    \"globalTeardown\": \"<rootDir>/jest/teardown.cjs\",
    \"watchPathIgnorePatterns\": [
      \"<rootDir>/.tmp\"
    ],
    \"moduleNameMapper\": {
      \"^~/(.*)$\": \"<rootDir>/src/$1\",
      \"^~components/(.*)$\": \"<rootDir>/src/components/$1\",
      \"^~util/(.*)$\": \"<rootDir>/src/util/$1\",
      \"^~types/(.*)$\": \"<rootDir>/src/types/$1\"
    }
  }

    标签: javascript node.js jestjs es6-modules ts-jest


    【解决方案1】:

    我遇到了同样的问题,它的修复方式与此评论中提到的相同:https://github.com/nrwl/nx/issues/812#issuecomment-429420861 在我的jest.config.js 中:

    // list to add ESM to ignore
    const esModules = ['uuid'].join('|');
    // ...
    module.exports = {
      //...
        transformIgnorePatterns: [`/node_modules/(?!${esModules})`],
      // ...
    };

    【讨论】:

      【解决方案2】:

      如果transformIgnorePatterns由于某种原因不起作用,您可以使用moduleNameMapper解决它。

          moduleNameMapper: {
              // '^uuid$': '<rootDir>/node_modules/uuid/dist/index.js',
              '^uuid$': require.resolve('uuid'),
          }
      

      【讨论】:

        猜你喜欢
        • 2020-08-07
        • 2021-10-26
        • 2018-07-14
        • 1970-01-01
        • 1970-01-01
        • 2019-04-27
        • 2022-07-10
        • 2020-08-12
        • 2017-06-08
        相关资源
        最近更新 更多