13

After adding the environment variable import.meta.env.VITE_* in my code, the tests with vue-test-utils started to fail, with the error:

Jest suite failed to run
error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node12', or 'nodenext'.

I have searched for some available fixes but none have worked so far.

EDIT

jest.config.js file:

module.exports = {
  preset: "ts-jest",
  globals: {},
  testEnvironment: "jsdom",
  transform: {
    "^.+\\.vue$": "@vue/vue3-jest",
    "^.+\\js$": "babel-jest"
  },
  moduleFileExtensions: ["vue", "js", "json", "jsx", "ts", "tsx", "node"],
  moduleNameMapper: {
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
      "<rootDir>/tests/unit/__mocks__/fileMock.js",
    "^@/(.*)$": "<rootDir>/src/$1"
  }
}

tsconfig.json file:

{
  "extends": "@vue/tsconfig/tsconfig.web.json",
  "include": ["env.d.ts", "src/**/*", "src/**/*.vue", "tests"],
  "compilerOptions": {
    "module": "esnext",
    "experimentalDecorators": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  },

  "references": [
    {
      "path": "./tsconfig.vite-config.json"
    }
  ]
}

When including module: "esnext", the warning below is displayed and the error remains.

Validation Warning:

Unknown option "module" with value "commonjs" was found. This is probably a typing mistake. Fixing it will remove this message.

Configuration Documentation: https://jestjs.io/docs/configuration

sfn
  • 263
  • 1
  • 2
  • 13

3 Answers3

20

Personally I route all my import.meta.env values through a single file (src/constants.ts or src/constants.js)

// src/constants.(js|ts)...

const {
  MODE: ENVIRONMENT,
} = import.meta.env;

export {
  ENVIRONMENT
};

Then in my jest tests I just mock the constants file:

// example.test.(js|ts)
jest.mock('src/constants', () => ({
  ENVIRONMENT: 'development',
}));

IMHO this is better also because you'll likely want to mock the value anyway.

nstanard
  • 593
  • 3
  • 12
  • 4
    This solution worked for me when 45 minutes of failed babel/jest related software dev acrobatics failed. It was simple and replaces all the difficult "modify your babel! install a plugin!" type solutions with something simple and direct. I recommend it to others. – plutownium Feb 17 '23 at 17:51
  • 1
    @plutownium <3 I also spent a good hour+ trying to modify configurations before I threw my hands up in the air and used jest mocking instead. Glad I could help! – nstanard Mar 15 '23 at 22:15
  • 1
    Does destructuring play nicely with vite's [static replacement](https://vitejs.dev/guide/env-and-mode.html#production-replacement)? – jeff Mar 24 '23 at 18:56
  • 1
    @jeff As far as I know - yes. I've been doing this approach for about six months without any issues. The app in all environments gets the right values set and exported from the constants file. And the jest tests work without having to do anything extra or special. :D – nstanard Apr 26 '23 at 14:56
  • 2
    Well, I love you. Maybe 3 hours spent in this #$%&. Just your answer could save me. Thanks. I think this must be marked as the correct answer. – Luis Jun 08 '23 at 04:01
  • Best answer, imo – Konstantin Komelin Jun 15 '23 at 00:05
8

After much research, I was able to solve the case.

I had to install the vite-plugin-environment and babel-plugin-transform-import-meta libraries and make the following settings:

babel.config.js

module.exports = {
  ...
  plugins: ["babel-plugin-transform-import-meta"]
}

tsonfig.json

{
  ...
  "compilerOptions": {
    "module": "esnext",
    ...
    "types": [
      "node"
    ]
  },
  ...
}

vite.config.ts

...
import EnvironmentPlugin from "vite-plugin-environment"
...
export default defineConfig({
  plugins: [..., EnvironmentPlugin("all")],
  ...
})

Also change the import.meta.env.* to process.env.*

sfn
  • 263
  • 1
  • 2
  • 13
0

If you are using react + vite, I tried the following:

npm install --save-dev dotenv cross-env

to get env in standard form, then I made the following configuration in my vite.config.js

export default defineConfig(({ command, mode }) => { 
  const env = loadEnv(mode, process.cwd(), '');
  return {
    plugins:[react()],
    server: {
      host:true
    },
    define: {
      'process.env.YOUR_STRING_VARIABLE': 
      JSON.stringify(env.YOUR_STRING_VARIABLE),
      'process.env.APP_USE_AVT': env.APP_USE_AVT,
    },
  };
});

this solved it.

sadeq shahmoradi
  • 1,395
  • 1
  • 6
  • 22