Skip to content

Latest commit

 

History

History
168 lines (144 loc) · 3.42 KB

esm-support.md

File metadata and controls

168 lines (144 loc) · 3.42 KB
id title
esm-support
ESM Support

To use ts-jest with ESM support:

ESM presets

There are also 3 presets to work with ESM.

Examples

Manual configuration

/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
  // [...]
  extensionsToTreatAsEsm: ['.ts'],
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1',
  },
  transform: {
    '<regex_match_files>': [
      'ts-jest',
      {
        useESM: true,
      },
    ],
  },
}
import type { JestConfigWithTsJest } from 'ts-jest'

const jestConfig: JestConfigWithTsJest = {
  // [...]
  extensionsToTreatAsEsm: ['.ts'],
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1',
  },
  transform: {
    '<regex_match_files>': [
      'ts-jest',
      {
        useESM: true,
      },
    ],
  },
}

export default jestConfig
{
  // [...]
  "jest": {
    "extensionsToTreatAsEsm": [".ts"],
    "moduleNameMapper": {
      "^(\\.{1,2}/.*)\\.js$": "$1"
    },
    "transform": {
      "<regex_match_files>": [
        "ts-jest",
        {
          "useESM": true
        }
      ]
    }
  }
}

Use ESM presets

:::important

Starting from v28.0.0, ts-jest will gradually switch to esbuild/swc to transform ts to js. To make the transition smoothly, we introduce legacy presets as a fallback when the new codes don't work yet.

:::

/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
  // [...]
  preset: 'ts-jest/presets/default-esm', // or other ESM presets
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1',
  },
  transform: {
    '<regex_match_files>': [
      'ts-jest',
      {
        useESM: true,
      },
    ],
  },
}
import type { JestConfigWithTsJest } from 'ts-jest'

const jestConfig: JestConfigWithTsJest = {
  // [...]
  preset: 'ts-jest/presets/default-esm', // or other ESM presets
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1',
  },
  transform: {
    '<regex_match_files>': [
      'ts-jest',
      {
        useESM: true,
      },
    ],
  },
}

export default jestConfig
{
  // [...]
  "jest": {
    "preset": "ts-jest/presets/default-esm", // or other ESM presets,
    "moduleNameMapper": {
      "^(\\.{1,2}/.*)\\.js$": "$1"
    },
    "transform": {
      "<regex_match_files>": [
        "ts-jest",
        {
          "useESM": true
        }
      ]
    }
  }
}

Support .mts extension

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:

{
  "compilerOptions": {
    "module": "Node16", // or "NodeNext"
    "target": "ESNext",
    "moduleResolution": "Node16", // or "NodeNext"
    "esModuleInterop": true
  }
}