How to import AMD javascript module into TypeScript external module?

How to import AMD javascript module into TypeScript external module?

I am using the TypeScript modular client program to use bower-driven AMD modules. As part of this process, the TypeScript module becomes the AMD javascript module, which I then publish. Now I have an AMD javascript module that I want to include in a TypeScript module, and I don't want to publish the original TypeScript with AMD javascript.

I cannot figure out how to write my TypeScript code so that it loads the AMD javascript module for which there is no corresponding TypeScript, and it seems that the latest versions of TypeScript do not support this yet.

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

File main.ts:

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

Log.ts file:

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

I believe that I need to change main.ts so that the compiler resolves the "log" link to the AMD log.js module. The following is the log.js file created by running tsc --module amd main.ts. This is the correct AMD module.

Log.js file:

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

To simulate the AMD javascript module, compile the above example and then delete the log.ts file. If now you try to compile 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 change main.ts so that it compiles and resolves this AMD log.js module? I can write a log.d.ts file if necessary, but would like to use a method that also works without a declaration file.

If I can learn how to do this in the canonical TypeScript path, I can continue to fully modulate my project.

+7
javascript module external amd typescript
source share
1 answer

How can I change main.ts so that I can download and use this AMD log.js module?

If you only access log.js, you can tell typescript about the type of information from log using declare ie create log.d.ts :

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

And then use it from main.ts like:

 /// <reference path='log.d.ts'/> import log = require('log'); log.message("hello"); 
+2
source share

All Articles