测试套件未能 运行 import.meta.env.VITE_*

Test suite failed to run import.meta.env.VITE_*

在我的代码中添加环境变量 import.meta.env.VITE_* 后,使用 vue-test-utils 的测试开始失败,错误为:

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'.

我已经搜索了一些可用的修复程序,但 none 到目前为止都有效。

编辑

jest.config.js 文件:

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/"
  }
}

tsconfig.json 文件:

{
  "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"
    }
  ]
}

当包含module: "esnext"时,会显示下面的警告,错误仍然存​​在。

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

经过大量研究,我终于破案了。

我必须安装 vite-plugin-environmentbabel-plugin-transform-import-meta 库并进行以下设置:

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")],
  ...
})

同时将 import.meta.env.* 更改为 process.env.*