“import.meta”元属性“--module”选项与 vite 错误并在 monorepo 中做出反应

问题描述 投票:0回答:1

错误 TS1343:仅当“--module”选项为“es2020”、“es2022”、“esnext”、“system”、“node16”或“nodenext”时,才允许使用“import.meta”元属性。 const chatApiUrl = import.meta.env.VITE_CHAT_API_URL || “”;

为 Nx monorepo React 工作区设置笑话测试配置。它使用 vite.config.ts 编写的玩笑单元测试用例因 import.meta 问题而失败。

这是 tsconfig.spec.json

{
    "extends": "./tsconfig.json",
    "compilerOptions": {
      "outDir": "./out-tsc/spec",
      "types": ["jest", "node"],
      "module": "esnext",
      "target": "esnext",
      "allowJs": true,
      "noEmit": true,
      "isolatedModules": true,
      "esModuleInterop": true,
      "skipLibCheck": true
    },
    "include": [
      "src/**/*.spec.ts",
      "src/**/*.spec.tsx",
      "src/**/*.d.ts"
    ]
  }

这是 tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "useDefineForClassFields": true,
    "lib": [
      "dom",
      "dom.iterable",
      "esnext",
      "es2020"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "sourceMap": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "preserveConstEnums": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "types": ["vite/client", "jest", "node"],
    "outDir": "dist"
  },
  "include": ["src/**/*.ts", "src/**/*.tsx", "tests/**/*.ts", "tests/**/*.tsx"],
  "exclude": ["node_modules"],
  "extends": "../../tsconfig.base.json"
}

这是 tsconfig.base.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "rootDir": ".",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "ES2020",
    "module": "esnext",
    "lib": ["es2020", "dom"],
    "skipLibCheck": true,
    "skipDefaultLibCheck": true,
    "baseUrl": ".",
    "paths": {}
  },
  "include": ["**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules", "dist", "tmp"]
}

这是 jest.preset.ts

const nxPreset = require('@nx/jest/preset').default;
module.exports = {
    ...nxPreset,
    testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'],
    transform: {
        '^.+\\.(ts|js|html)$': 'ts-jest',
    },
    resolver: '@nx/jest/plugins/resolver',
    moduleFileExtensions: ['ts', 'js', 'html'],
    coverageReporters: ['html'],
};

这是jest.config.ts

import { getJestProjects } from '@nx/jest';

export default {
  projects: getJestProjects(),
  setupFiles: ['./jest.setup.ts'],
};

VITE_CHAT_API_URL 在 .env.test 文件中定义。测试用例是在代码中编写的,其中 React 使用 signalR 与后端通信

const BACKEND_URI = "";
const chatApiUrl = import.meta.env.VITE_CHAT_API_URL || "";
const connection = new signalR.HubConnectionBuilder()
    .withUrl(chatApiUrl, { withCredentials: false })
    .build();

connection.start()
    .then(() => console.log("Connected to SignalR hub"))
    .catch(err => console.error("Error connecting to SignalR hub: ", err));

这是规格文件

import { getHeaders } from './api';

describe('getHeaders', () => {
    it('should return the Authorization header if useLogin is true, isUsingAppServicesLogin is false, and idToken is provided', async () => {
        const headers = await getHeaders('some-id-token');
        expect(headers).toEqual({ Authorization: 'Bearer some-id-token' });
    });
});

通过更新 tsconfig 文件尝试了多种方法,但更新不起作用。想获得一些帮助。

reactjs jestjs signalr vite monorepo
1个回答
0
投票

import.meta 特定于 ES 模块和 Vite,Jest 本身不支持。由于 Jest 不直接支持 import.meta.env,因此您可以通过在 Jest 中模拟它或使用 vite-jest 或 vite-plugin-env-completed 等库来解决此问题

© www.soinside.com 2019 - 2024. All rights reserved.