Search code examples
node.jstypescriptnamespacestsc

tsc generated .d.ts files giving error "Cannot find namespace 'Jimp'"


I'm working on an NPM package, and one of my classes is simply this:

import { MIME_PNG } from 'jimp';
import { IDimensions } from './spritesheet';

/**
 * A class for a single sprite. This contains the image
 * and supporting data and methods
 */
export class Sprite {
    image: Jimp.Jimp;
    dimensions: IDimensions;

    /**
     * 
     * @param img a jimp image of the sprite
     */
    constructor (img: Jimp.Jimp) {
        this.image = img;

        this.dimensions = {
            width: this.image.bitmap.width,
            height: this.image.bitmap.height
        }
    }

    /**
     * Get the buffer for the sprite. Returns a promise.
     */
    getBuffer (): Promise<Buffer> {
        return new Promise((resolve, reject) => {
            return this.image.getBuffer(MIME_PNG, (err, buff) => {
                if (err) return reject(err);

                resolve(buff);
            });
        });
    }
}

Typescript compiles this fine with just the command tsc, but when I publish the package I'm compiling with the command tsc -d -p ./ --outdir dist/ to generate .d.ts files.

The outputted file looks like this:

/// <reference types="node" />
import { IDimensions } from './spritesheet';
/**
 * A class for a single sprite. This contains the image
 * and supporting data and methods
 */
export declare class Sprite {
    image: Jimp.Jimp;
    dimensions: IDimensions;
    /**
     *
     * @param img a jimp image of the sprite
     */
    constructor(img: Jimp.Jimp);
    /**
     * Get the buffer for the sprite. Returns a promise.
     */
    getBuffer(): Promise<Buffer>;
}

Now, when viewing this file in VSCode, and when publishing/importing into a different project, I get typescript errors on the Jimp.Jimp types saying "Cannot find namespace 'Jimp'."

I noticed tsc is dropping the import { MIME_PNG } from 'jimp'; line from the file and, if I add that file back, it compiles just fine.

My tsconfig.json file looks like this:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "sourceMap": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "moduleResolution": "node"
  }
}

Solution

  • I had the same issue as you. I was able to solve it by adding a reference path to the .d.ts jimp file at the top of the .ts file where I import the stuff from Jimp.

    So before import { MIME_PNG } from 'jimp';

    you should add /// <reference path="../../node_modules/jimp/jimp.d.ts" />

    This way it seems that Typescript is able to find the Jimp namespace.