Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I import a javascript AMD module into an external TypeScript module?

How can I import a javascript AMD module into a external TypeScript module?

I'm modularizing my client TypeScript program to use AMD modules managed by bower. As part of this process, a Typescript module becomes a javascript AMD module, which I then publish. Now I have a javascript AMD module that I want to include in a TypeScript module, and I don't want to publish the original TypeScript with the javascript AMD.

I cannot figure out how to write my TypeScript code so that it will load a javascript AMD module for which there is no corresponding TypeScript, and it appears that the most recent versions of TypeScript don't support this yet.

If I start with the example from the 0.9.7 TypeScript specification, section 11.2:

File main.ts:

import log = require("./log"); 
log.message("hello"); 

File log.ts:

export function message(s: string) { 
    console.log(s); 
}

I believe I should be able to modify main.ts so that the compiler resolves the "log" reference to the log.js AMD module. Below is the log.js file that was produced by running tsc --module amd main.ts. It is a correct AMD module.

File log.js:

define(["require", "exports"], function(require, exports) {
    function message(s) {
        console.log(s);
    }
    exports.message = message;
});

To simulate having a javascript AMD module, compile the above example, and then delete the log.ts file. If you now try to compile using the same command, it fails with the following errors:

./main.ts(1,1): error TS2071: Unable to resolve external module '"./log"'.  
./main.ts(1,1): error TS2072: Module cannot be aliased to a non-module type.

How can I now modify main.ts so it compiles and resolves against this log.js AMD module? I can write log.d.ts file if I have to, but would like a method that also works without a declaration file.

If I can learn how to do this in the canonical TypeScript Way, then I can continue the complete modularization of my project.

like image 456
psnider Avatar asked Mar 29 '14 21:03

psnider


1 Answers

How can I now modify main.ts so I can load and use this log.js AMD module?

If you only the log.js available you can tell typescript about the type information from log using declare i.e. create a log.d.ts:

declare module 'log'{
    export function message(s:string);
}

And then use it from main.ts as :

/// <reference path='log.d.ts'/>    

import log = require('log'); 
log.message("hello"); 
like image 92
basarat Avatar answered Oct 15 '22 22:10

basarat