Search code examples
modulerequirejstypescriptamd

Import an AMD JS library in a TypeScript file


I'm stuck with the right way to import an AMD JavaScript library (https://github.com/dcodeIO/bytebuffer.js) into a TypeScript file.

I found its - not up-to-date - type definition (https://github.com/SINTEF-9012/Proto2TypeScript/commit/0889dccbf6048f116551a73e77d75dd83553cfe6), but actually I was not able to find a way to use it and have the library loaded by RequireJS.

This is the code I'm using:

/// <amd-dependency path="Scripts/bytebuffer" />
var ByteBuffer = require( 'Scripts/bytebuffer' );

import protocols = require( 'protocols' );

export class Pippo
{
    readPayload( payload: ArrayBuffer, ECType: string ): any
    {
        var ECStruct = new protocols.ECStruct( ECType );

        var bb = new ByteBuffer()
            .writeIString( "Hello world!" )
            .flip();
        console.log( bb.readIString() + " from bytebuffer.js" );
    }
}

The two modules protocols and bytebuffer are loaded correctly, but actually I cannot see members of instance bb in Visual Studio. If I put the line

/// <reference path="scripts/typings/bytebuffer/bytebuffer.d.ts" />

and comment //var ByteBuffer = require( 'Scripts/bytebuffer' ); of course I can see methods and properties of bb, but the module is not loaded at runtime.

Is there a way to have the ByteBuffer.js loaded by RequireJS with the possibility to see its members in VS?

Thanks


Solution

  • There is a syntax for declaring the interface of external modules:

    declare module 'amd/module/name' {
        // module definition, probably with:
        exports = thingToExport;
    }
    

    In your case it should probably be:

    declare module 'Scripts/bytebuffer' {
        exports = ByteBuffer;
    }
    

    Put this after the bytebuffer.d.ts file!!! Also see "Writing .d.ts files" in the handbook.

    In my case the /// <amd-dependency> and /// <reference> stuff were also redundant - you may want to try it too, to simplify your code.