问题描述
我希望从JavaScript切换到TypeScript,以帮助我们的项目变得更大的代码管理。然而,我们使用许多库作为amd模块,我们不想将其转换为TypeScript。
I want to switch from JavaScript to TypeScript to help with code management as our project gets larger. We utilize, however, lots of libraries as amd Modules, which we do not want to convert to TypeScript.
我们仍然希望将它们导入到TypeScript文件中,但我们也是不想生成定义文件。我们怎样才能做到这一点?
We still want to import them into TypeScript files, but we also do not want to generate definition files. How can we achieve that?
例如。新的Typescript文件:
e.g. The new Typescript file:
/// <reference path="../../../../definetelyTyped/jquery.d.ts" />
/// <reference path="../../../../definetelyTyped/require.d.ts" />
import $ = require('jquery');
import alert = require('lib/errorInfoHandler');
这里, lib / errorInfoHandler
是一个amd模块包含在我们不想触摸的巨大JavaScript库中。
Here, lib/errorInfoHandler
is an amd module included in a huge JavaScript library that we do not want to touch.
使用上面的代码会产生以下错误:
Using the above code produces the following errors:
Unable to resolve external module ''lib/errorInfoHandler''
Module cannot be aliased to a non-module type.
这实际上应该产生以下代码:
This should actually produce the following code:
define(["require", "exports", "jquery", "lib/errorInfoHandler"], function(require, exports, $, alert) {
...
}
有没有办法将JavaScript库导入TypeScript作为amd模块并在TypeScript文件中使用它而不制作定义文件?
Is there a way to import a JavaScript library into TypeScript as an amd Module and use it inside the TypeScript file without making a definition file?
推荐答案
这里给出的2个答案的组合为我工作。
A combination of the 2 answers given here worked for me.
//errorInfoHandler.d.ts
declare module "lib/errorInfoHandler" {
var noTypeInfoYet: any; // any var name here really
export = noTypeInfoYet;
}
我还是TypeScript的新手,但看起来这只是一种告诉TypeScript通过导出没有类型信息的虚拟变量而离开的方法。
I'm still new to TypeScript but it looks as if this is just a way to tell TypeScript to leave off by exporting a dummy variable with no type information on it.
编辑
在评论中已注明这个答案可以通过简单地声明来实现相同的结果:
It has been noted in the comments for this answer that you can achieve the same result by simply declaring:
//errorInfoHandler.d.ts
declare module "*";
请参阅github评论。
See the github comment here.
这篇关于如何在typescript文件中导入没有定义文件的js库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!