You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mocha无法为ESM导入使用TypeScript baseUrl配置的问题求助

如何让Mocha测试文件中的绝对导入路径在Vite/TS React项目中生效

我正在尝试让Mocha测试文件中的绝对导入路径生效,这类路径在我们的Vite/TS React项目里能正常工作。示例导入语句:
import { agent } from 'tests/shared/supertest'

我已按照建议在配置中添加ts-node/tsconfig-paths,但仍报错:
Cannot find package 'tests' imported from tests\configs\mocha\setup.ts

我也尝试过使用ts-mocha,但在我们的ESM场景下同样无法正常工作。


相关配置文件

.mocharc.json

{
  "extensions": ["ts"],
  "node-option": ["experimental-specifier-resolution=node", "loader=ts-node/esm", "no-warnings"],
  "require": [
    "ts-node/register",
    "tsconfig-paths/register",
    "tests/configs/mocha/setup.ts",
    "tests/configs/mocha/teardown.ts",
    "jsdom-global/register"
  ],
  "slow": 5000,
  "timeout": 60000
}

tsconfig.node.json

{
  "compilerOptions": {
    "composite": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "allowSyntheticDefaultImports": true,
    "baseUrl": "."
  },
  "include": ["vite.config.ts"]
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "baseUrl": "."
  },
  "include": ["app", "./tests/**/*.ts", ".storybook/*.ts", ".storybook/*.tsx", "./playwright.config.ts", "*.ts"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

内容的提问来源于stack exchange,提问作者helion3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 06:05:05