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

梦想与她 提交于 2019-12-10 13:22:31

问题


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.


回答1:


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"); 


来源:https://stackoverflow.com/questions/22737337/how-can-i-import-a-javascript-amd-module-into-an-external-typescript-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!