ts-jest: [Bug]: error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'.

[For context, I originally opened this issue in the jest repo, but @SimenB said I should open a ticket here.]

Version

29.0.3

Steps to reproduce

Expected behavior

Test should run w/out errors.

Actual behavior

Test fails with the error shown in the title.

Specifically, here’s what I see: CleanShot 2022-10-26 at 17 17 13@2x

Additional context

You can click “show files” in the repl.it window to see the tsconfig.json and package.json#jest setup.

As you’ll see, I have the following configuration, so it’s not clear what else I could/should do to work around this error:

{
  "compilerOptions": {
    "module": "es2020",
    "moduleResolution": "node",
    "target": "es2020",
    "esModuleInterop": true,
    "types": [
      "jest"
    ]
  }
}

Environment

~/JestImportMetaTest$ npx envinfo --preset jest.
Need to install the following packages:
  envinfo
Ok to proceed? (y) y

No "jest." preset found.
npm notice 
npm notice New major version of npm available! 7.20.3 -> 8.19.2
npm notice Changelog: https://github.com/npm/cli/releases/tag/v8.19.2
npm notice Run npm install -g npm@8.19.2 to update!
npm notice 
~/JestImportMetaTest$

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 36
  • Comments: 25

Commits related to this issue

Most upvoted comments

I’ve linked the example repos. You can check them.

Okay, I think I have this figured out. Debugging this was complicated by the fact there were two issues, either one of which would result in the same (not-at-all obvious) error message. Leaving breadcrumbs for anyone else who struggles with this…

The two missing pieces (for me) were the following:

  1. jest has to be run with node’s --experimental-vm-modules flag. I.e. Invoke jest as NODE_OPTIONS="--experimental-vm-modules" jest.
  2. Configure jest with the ts-jest/presets/default-esm preset:
module.exports = {
  preset: 'ts-jest/presets/default-esm',
}

Sorry for the trouble @ahnpnl . I appreciate your patience. 🙌

@ahnpnl I’ve just spent the last half-hour reading the docs you linked to and trying every combination of tsconfig and jest.config.js I could find therein. Including …

  • Moving jest config out of package.json and into jest.config.js
  • Switching from "presets": "ts-jest" to "presets": "ts-jest/presets/default-esm"
  • Removing presets
  • Adding "useESM": true
  • Switching to "module": "CommonJS" in tsconfig
  • Adding/removing tsconfig: 'tsconfig.json', in tsconfig
  • Removing types, target, and moduleResolution in tsconfing

… and nothing helps. I keep getting the same error message.

I apologize for the trouble, but can you please tell me what configuration exactly I should be using here to get this to work?

Alternatively, you can use ts-jest-mock-import-meta npm package to fix this issue.

Install

npm install -D ts-jest-mock-import-meta

In jest.config.js

{
  // [...]
  transform: {
    '^.+\\.tsx?$': [
      'ts-jest',
      {
        diagnostics: {
          ignoreCodes: [1343]
        },
        astTransformers: {
          before: [
            {
              path: 'node_modules/ts-jest-mock-import-meta',  // or, alternatively, 'ts-jest-mock-import-meta' directly, without node_modules.
              options: { metaObjectReplacement: { url: 'https://www.url.com' } }
            }
          ]
        }
      }
    ]
  }
}

Alternatively, you can use ts-jest-mock-import-meta npm package to fix this issue.

Install

npm install -D ts-jest-mock-import-meta

In jest.config.js

{
  // [...]
  transform: {
    '^.+\\.tsx?$': [
      'ts-jest',
      {
        diagnostics: {
          ignoreCodes: [1343]
        },
        astTransformers: {
          before: [
            {
              path: 'node_modules/ts-jest-mock-import-meta',  // or, alternatively, 'ts-jest-mock-import-meta' directly, without node_modules.
              options: { metaObjectReplacement: { url: 'https://www.url.com' } }
            }
          ]
        }
      }
    ]
  }
}

this did solve the issue. 👌

tried it in an esModule project and the package references above causes an error saying the __filename has already been defined.

There is an open issue on his site with no fix/answer:

https://github.com/ThomZz/ts-jest-mock-import-meta/issues/5

I can’t believe after all these years, using modules is still so hard and cumbersome/broken 👎

@broofa Your first suggestion does not work for me. With that setting I now get the error:

ReferenceError: exports is not defined

so as if jest would try with common js modules, instead of ESM.

Configuring jest-ts-webcompat-resolver helped me in the same situation, I have no idea how

Hello, Did anyone find a solution to this issue? I have been trying to solve it for 5 days now. I would really appreciate some help .

I have tried the configurations that was suggested in this discussion. I am leaving my configurations below, let me know if I am doing anything wrong.

Error I am receiving

FAIL tests/build-meetings.test.js
  ΓùÅ Test suite failed to run

    scripts/build-meetings.ts:7:39 - error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'.

    7 const currentFilePath = fileURLToPath(import.meta.url);
                                            ~~~~~~~~~~~
    scripts/build-meetings.ts:73:39 - error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'.

    73 if (process.argv[1] === fileURLToPath(import.meta.url)) {
                                             ~~~~~~~~~~~

My jest.config.cjs File

image

My tsconfig.json file

image

cc: @ahnpnl

Update: I have solve the issue by using babel with babel-plugin-transform-import-meta.

Hey folks,

Shockingly enough, following what was in the example folders fixed the issue in minutes for me. The example folder now uses a function from ts-jest to generate the right preset info, and in that function you ought to pass the tsconfig.json file to use.

With minor adjustments to match my project structure, I ended up with the following:

import { createDefaultEsmPreset } from 'ts-jest'

/** @type {import('ts-jest').JestConfigWithTsJest} */
export default {
  roots: ['<rootDir>'],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  // Other stuff like coverage options, etc.
  ...createDefaultEsmPreset({
    tsconfig: 'tsconfig-esm.json',
  }),
}

Alternatively, you can use ts-jest-mock-import-meta npm package to fix this issue.

Install

npm install -D ts-jest-mock-import-meta

In jest.config.js

{
  // [...]
  transform: {
    '^.+\\.tsx?$': [
      'ts-jest',
      {
        diagnostics: {
          ignoreCodes: [1343]
        },
        astTransformers: {
          before: [
            {
              path: 'node_modules/ts-jest-mock-import-meta',  // or, alternatively, 'ts-jest-mock-import-meta' directly, without node_modules.
              options: { metaObjectReplacement: { url: 'https://www.url.com' } }
            }
          ]
        }
      }
    ]
  }
}

It worked for me! thank you very much 🫡

In each example project, there is a jest-esm.config.js which already points to the tsconfig.json it is using. Besides, in package.json, the script to run test already contains the flag to use ESM with NodeJS.

Besides, if you are specifying transform, please remove preset from your Jest config.

The easiest way is you can clone one of the example apps and try out to compare with your repo. These example apps are included in CI so they are a good basic ones to start with.

Why do I still have to use NODE_OPTIONS="--experimental-vm-modules" jest in (almost) 2025? Looking at the example repo in type-module I see six configuration files. SIX!

Is all this really necessary to run a simple "test": "jest" script and file like example.test.ts with

it("should ran the darn test", () => {
    expect(true).toBeTruthy();
})

If you encounter this issue, I found that the simplest solution was to mock a constants file, as described in this stack overflow thread.

@broofa Your first suggestion does not work for me. With that setting I now get the error:

ReferenceError: exports is not defined

so as if jest would try with common js modules, instead of ESM.

I am getting this same error, even with the following:

import { jsWithTsESM } from "ts-jest/presets";

/*
 * For a detailed explanation regarding each configuration property and type check, visit:
 * https://jestjs.io/docs/configuration
 */

export default {
  ...jsWithTsESM,
  transform: {
    "^.+\\.tsx?$": [
      "ts-jest",
      {
        tsconfig: "tsconfig.json",
        useESM: true,
      },
    ],
  },
};

and

    "test": "cross-env NODE_OPTIONS=\"--experimental-vm-modules\" jest",