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

TypeScript读取api.json报错,已声明模块仍无法解决,求解决方案

解决JSON.parse报错与TypeScript JSON导入问题

从你的错误信息和编译后的代码来看,核心问题有两个:一是Grunt的@api替换逻辑没有正确生效,导致_apisConfig变成了空字符串,触发JSON.parse的语法错误;二是你尝试用TypeScript处理JSON文件的方式可以更规范。下面分两种方案来解决:

方案一:修复Grunt替换逻辑(保持现有构建流程)

你的代码依赖Grunt在构建前把@api替换成api.json的内容,但从编译后的index.js里this._apisConfig = ''可以看出,替换步骤没有正确执行。你需要检查并调整Grunt配置:

  1. 确保安装并配置grunt-replace插件
    首先安装插件:

    npm install grunt-replace --save-dev
    

    然后在Gruntfile.js里添加替换任务,注意要把JSON内容转义成合法的字符串字面量:

    const fs = require('fs');
    
    grunt.initConfig({
      replace: {
        injectApiConfig: {
          options: {
            patterns: [
              {
                match: '@api',
                replacement: function() {
                  // 读取api.json内容,转义后作为字符串嵌入代码
                  const rawJson = fs.readFileSync('./api.json', 'utf8');
                  // 转义双引号和换行,避免破坏TS代码的字符串结构
                  return JSON.stringify(rawJson);
                }
              }
            ]
          },
          files: [
            { src: ['index.ts'], dest: 'index.ts' } // 直接修改源文件,或者输出到构建目录
          ]
        }
      }
    });
    
    grunt.loadNpmTasks('grunt-replace');
    // 确保替换任务在TypeScript编译前执行
    grunt.registerTask('build', ['replace:injectApiConfig', 'ts:compile']);
    
  2. 检查构建顺序
    一定要让Grunt的替换任务在TypeScript编译任务之前运行,否则TS编译时@api还是未替换的状态,最终会被编译成空字符串。

方案二:改用TypeScript原生导入JSON(更简洁规范)

既然你已经添加了declare module "*.json"的声明,不如直接用TypeScript的JSON导入功能,彻底去掉Grunt的替换逻辑,更符合TS的开发习惯:

  1. 完善TypeScript配置

    • 如果你的TypeScript版本在2.9以上,直接在tsconfig.json里开启:
      {
        "compilerOptions": {
          "resolveJsonModule": true,
          "esModuleInterop": true
        }
      }
      
    • 如果版本较低,保持你已有的declare module "*.json"声明(放在项目的typings.d.ts或其他类型声明文件中),还可以把类型写得更具体:
      declare module "*.json" {
        const value: {
          Refills: {
            getPatientInfo: string;
          };
        };
        export default value;
      }
      
  2. 修改index.ts代码
    直接导入api.json,去掉_apisConfig和JSON.parse的部分:

    import { ModuleExecutor } from "./common/ModuleExecutor";
    import { Identity } from "./common/Enums";
    import apiConfig from "./api.json"; // 直接导入JSON模块
    
    export class Index {
      private executor: ModuleExecutor = null;
    
      constructor(identity: string) {
        this.executor = new ModuleExecutor(Identity[identity]);
        console.log('API', apiConfig);
        for (const module in apiConfig) {
          if (apiConfig.hasOwnProperty(module)) {
            this[module] = {};
            for (const api in apiConfig[module]) {
              if (apiConfig[module].hasOwnProperty(api)) {
                this[module][api] = this.executor.execute(apiConfig[module][api]);
              }
            }
          }
        }
      }
    }
    

这样修改后,TypeScript会在编译时自动处理JSON文件,不需要依赖Grunt的替换,也不会出现JSON.parse的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:25:37