Skip to main content
Version: Next

ESM Support

References


Configuration

To use ts-jest with ESM support:

Example:

// tsconfig.spec.json
{
"compilerOptions": {
"module": "ESNext", // or ES2022
"target": "ESNext",
"esModuleInterop": true
}
}

Example:

// jest.config.mts
import { createDefaultEsmPreset, type JestConfigWithTsJest } from 'ts-jest'

const presetConfig = createDefaultEsmPreset({
//...options
})

const jestConfig: JestConfigWithTsJest = {
...presetConfig,
}

export default jestConfig

Resolve .mjs/.mts extensions

To work with .mts extension, besides the requirement to run Jest and ts-jest in ESM mode, there are a few extra requirements to be met:

  • package.json should contain "type": "module"
  • A custom Jest resolver to resolve .mjs extension, for example:
import type { SyncResolver } from 'jest-resolve'

const mjsResolver: SyncResolver = (path, options) => {
const mjsExtRegex = /\.mjs$/i
const resolver = options.defaultResolver
if (mjsExtRegex.test(path)) {
try {
return resolver(path.replace(mjsExtRegex, '.mts'), options)
} catch {
// use default resolver
}
}

return resolver(path, options)
}

export = mjsResolver