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

使用tsconfig paths配置时TypeScript无法导入JSON文件的问题排查

JSON文件别名导入问题排查与解决

问题背景

使用别名导入JSON文件时触发错误:

import Rush from '@mocks/rush.json';

错误提示:

Cannot find module '@mocks/rush.json'. Consider using '--resolveJsonModule' to import module with '.json' extension.

按照提示更新tsconfig.json后:

{
    "compilerOptions": {
        "moduleResolution": "Node",
        "target": "ES2020",
        "sourceMap": true,
        "resolveJsonModule": true,
        "esModuleInterop": true,
        "paths": {
            "@mocks/*": ["../mocks/*"],
            "@root/*": ["../*"],
            "@src/*": ["./*"]
        },
    },
}

但错误依然存在,而使用相对路径导入则正常:

import Rush from '../../mocks/rush.json';

添加"baseUrl": "./src"后编译正常,但Mocha Test Explorer仍报错:

Cannot find module '@mocks/rush.json'

问题原因与解决方法

1. 别名解析必须配合baseUrl

TypeScript的paths配置依赖baseUrl才能生效,你添加baseUrl后编译正常,说明这一步修正了编译阶段的路径解析问题,但Mocha测试环境没有识别到TypeScript的路径映射规则。

2. 适配Mocha环境的别名解析

Mocha本身不读取tsconfig.json的paths配置,需要额外配置路径注册:

  • 安装依赖包:
    npm install tsconfig-paths --save-dev
    
  • 修改package.json的测试脚本,添加路径注册器:
    "scripts": {
      "test": "mocha -r ts-node/register -r tsconfig-paths/register src/**/*.test.ts"
    }
    
  • 若使用VS Code的Mocha Test Explorer,在.vscode/settings.json中添加配置:
    {
      "mochaExplorer.require": ["ts-node/register", "tsconfig-paths/register"]
    }
    

3. 验证路径映射的正确性

确保@mocks/*对应的物理路径与项目结构匹配:
假设项目结构为:

项目根目录/
├── mocks/
│   └── rush.json
└── src/
    ├── tsconfig.json
    └── 业务文件.ts

那么"@mocks/*": ["../mocks/*"]配合baseUrl: "./src",TypeScript会正确将@mocks/rush.json解析为项目根目录下的mocks/rush.json。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 03:18:16