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

在TypeScript/Angular项目中引入无类型定义的SongPro包遇阻求助

解决TypeScript/Angular中使用SongPro包的问题

1. 修正自定义类型声明并配置TS识别

你的类型声明存在结构错误,且需要确保TypeScript能正确识别声明文件:

步骤1:调整类型声明文件内容

在项目src目录下创建types/songpro.d.ts(更符合Angular项目结构),内容如下:

declare module 'songpro' {
  export interface SongSection {
    type: string;
    name?: string;
    lines: string[];
  }

  export interface Song {
    title: string;
    artist?: string;
    sections: SongSection[];
    // 可根据包的实际返回结构,补充album、key等字段
  }

  export function parse(contents: string | Buffer): Song;
}

步骤2:配置tsconfig.json

确保tsconfig.json的include数组包含类型声明目录,让TS能扫描到:

{
  "compilerOptions": {
    // 保留原有配置
  },
  "include": [
    "src/**/*",
    "src/types/**/*.d.ts"
  ]
}

2. 解决导入后为空对象的问题

空对象问题源于SongPro采用CommonJS格式导出,与TS模块解析规则不匹配,可通过以下方式解决:

方式1:使用TS的CommonJS导入语法

import songpro = require('songpro');

// 使用示例
const songData = songpro.parse(`
title: Demo Song
artist: Test Artist

[Verse 1]
First line of verse
Second line of verse
`);

方式2:启用ES模块兼容配置

若偏好ES模块语法,在tsconfig.json的compilerOptions中添加:

{
  "compilerOptions": {
    // 保留原有配置
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true
  }
}

之后即可用ES模块导入:

import songpro from 'songpro';

// 使用方式同上

3. 验证与排查

  • 确保安装的是最新版SongPro:
    npm install songpro --save
    
  • 若仍为空对象,直接查看node_modules/songpro/dist/songpro.js的导出结构,确认类型声明的导出与实际一致(比如包是否通过module.exports = { parse: ... }导出)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:22:41