admin管理员组

文章数量:1332597

I can run my ESM .spec files with Jest. My question is about loading jest.config.ts file itself (rather than .spec.ts files) as ESM instead of CommonJS.

The file jest.config.ts imports an ESM module such as such as strip-json-comments (versions > 4.0 only support ESM).

jest.config.ts:

import strip from 'strip-json-comments' 

export default function config(){
  // call the esm function
  strip(...);
}

This causes the following error:

Error: Jest: Failed to parse the TypeScript config file jest.config.ts
  Error [ERR_REQUIRE_ESM]: require() of ES Module node_modules/.pnpm/[email protected]/node_modules/strip-json-comments/index.js from jest.config.ts not supported.
Instead change the require of index.js in jest.config.ts to a dynamic import() which is available in all CommonJS modules.

Please note that the ESM spec files can run normally, i.e. not importing any ESM module inside jest.config.ts not causing this error.

I added "type": "module" in package.json and run Jest like that:

node --loader ts-node/esm --experimental-specifier-resolution=node --experimental-import-meta-resolve --experimental-vm-modules node_modules/jest/bin/jest.js

minimal reproduction

本文标签: nodejsHow to make Jest read jestconfig file (not spec files) as ESMStack Overflow