Including JS package import in a TypeScript project

251 Views Asked by At

I'm working on a TypeScript/Angular project, and I've found a package I'd like to use with it called SongPro that will help me parse some files. Here is that project on GitHub and NPM.

This project has no Type definitions and I'm not really sure how to include it in my project. I've read about how to get around this my creating some fake/temp typedefs like this:

File: songpro.d.ts

declare module "*";

And then somewhere in my project:

import * as songpro from 'songpro'

console.log(songpro);

That log produces only an empty object {}. I would have expected either a populated object or maybe even undefined, but an empty object is strange. I'm at a loss for what's going on. How can I use this package in my project?


Edit

Editing based on what I've tried with the answer from Arjis Chakraborty below.

I have created the file ./typings/songpro.d.ts with this content:

declare module 'songpro' {
  export interface ISongDetails {
    title: string;
    artist: string;
    sections: ISongDetails[];
  }
  export function parse(contents: string | Buffer): ISongDetails;
}

Now when I have the following in my project:

import * as songpro from 'songpro'

console.log(songpro);

the imported songpro object seems to recognise the typedefs that are declared

enter image description here

However when I build the project I get this error:

- error TS7016: Could not find a declaration file for module 'songpro'. 'C:/Users/FiniteLooper/Projects/LyricConverter/node_modules/songpro/dist/songpro.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/songpro` if it exists or add a new declaration (.d.ts) file containing `declare module 'songpro';`

1 import * as songpro from 'songpro'
                           ~~~~~~~~~

That message tells me to declare a module in a .d.ts file which I have already done and it can see! What is going on?

(And no, sadly there is no @types/songpro project)

However, if I do this:

const songpro = require('songpro');

console.log(songpro);

then I am back to getting an empty object logged out to the console with no build errors.

enter image description here

But if I use a capitalized SongPro instead of lower case

const songpro = require('SongPro');

console.log(songpro);

Then I get an empty object logged out in a different way

SongPro

I am very unclear on what is going wrong here.

1

There are 1 best solutions below

2
On

This should help

declare module songpro {
    interface ISongDetails {
        title: string;
        artist: string;
        sections: ISongDetails[];
    }
    function parse(contents: string | Buffer) : ISongDetails;
}