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

TypeScript项目中如何在index.ts导出JSON并配置tsconfig paths使用

问题根因

JSON 模块在 TypeScript 的 ES 模块体系下仅存在 default 默认导出,不存在独立的命名导出,你使用的 export * as configFiles from "./config" 是抓取目标模块所有命名导出的语法,自然无法获取到JSON文件的内容,所以写法失效。

解决步骤

1. 调整 tsconfig 基础配置

首先在 compilerOptions 中新增以下配置,开启JSON模块解析支持:

{
  "compilerOptions": {
    // 新增这两行
    "resolveJsonModule": true,
    "esModuleInterop": true,
    // 如果需要省略导入时的.json后缀,可新增这行配置
    "moduleSuffixes": [".ts", ".tsx", ".json", ".js", ".jsx"],
    "paths": {
      "@errorClass": ["src/helpers/errorClasses"],
      "@config": ["src/config"],
      "@routes": ["src/routes"]
    }
  }
}

2. 编写 index.ts 导出语句

在你 src/config 文件夹下的 index.ts 文件中,使用默认导出重命名的语法导出JSON文件:

// 注意如果没有配置moduleSuffixes省略后缀,需要补全.json后缀
export { default as configFiles } from "./config.json";

如果需要导出多个JSON文件,可以批量编写导出语句:

export { default as appConfig } from "./app.json";
export { default as dbConfig } from "./db.json";

如果希望JSON作为当前目录的默认导出,可写为:

export { default } from "./config.json";
导入使用示例

完成上述配置后,即可在项目任意位置通过paths别名直接导入:

// 命名导出的导入方式
import { configFiles } from "@config";
// 默认导出的导入方式
import configFiles from "@config";

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 04:30:01