Testing React app with Jest, using Vite as a module Bundler; import.meta error

i am testing a React-Typescript application with Jest; my application uses Vite as a module bundler. The issue is, everytime i run tests and jest encounters an import.meta.ENV_VAR_NAME statement i get the following error: "SyntaxError: Cannot use 'import.meta' outside a module"

This is my jest.config.js file:

module.exports = {
roots: ["<rootDir>/src"],
setupFilesAfterEnv: ["<rootDir>/jest/jest.setup.js"],
collectCoverageFrom: ["src//*.{js,jsx,ts,tsx}", "!src//.d.ts"],
testMatch: [
testEnvironment: "jsdom",
transform: {
    // "^.+\.(js|jsx|mjs|cjs|ts|tsx)$": "esbuild-jest",
    "^.+\.(js|jsx|mjs|cjs|ts|tsx)$": "@swc/jest",
    "^.+\.scss$": "jest-scss-transform",
    "^.+\.css$": "<rootDir>/jest/mocks/cssMock.js"
transformIgnorePatterns: [
watchPlugins: [
resetMocks: true,
moduleDirectories: ["node_modules", "src"],
moduleNameMapper: {
    "\.worker": "<rootDir>/src/seo/mocks/workerMock.ts",
    "\.(css|sass|scss)$": "identity-obj-proxy"

In transform key of jest.config i tried using either @swc/jest and esbuild-jest, but none fixed the import.meta issue; is there a solution to this problem? Can i achieve it without using Babel?

Thanks in advance for your time


    • refer the above link for setting up Jest in your Vite project.
    • install this plugin (
    • create .env file in your project root folder near package.json
    • provide your env variables in .env files
    • change all your import.meta.env.YOUR_VAR to process.env.YOUR_VAR
    • open vite.config.ts and import import EnvironmentPlugin from 'vite-plugin-environment';
    • add EnvironmentPlugin('all') in plugins. example: plugins: [react(), EnvironmentPlugin('all')]
    • now your test will pass without import.meta.env error.
    • the explanation behind this config is that Jest will understand process.env.YOUR_VAR, so if you change all your import.meta.env.YOUR_VAR to process.env.YOUR_VAR then Jest will not give error.
    • But then we have to provide vite-plugin-environment to Vite Config so that it understands process.env.YOUR_VAR
    • it works in production as well.