使用TypeScript,有没有办法import
一个被webpack UMD(通用模块定义)包装的模块? 例如:
npm install knockback
.js文件 ( node_modules/knockback/knockback.js
) 的开头是这样的:
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("knockout"), require("backbone"), ....
else if(typeof define === 'function' && define.amd)
define(["knockout", "backbone", "underscore"], function webpackLoadOptionalExternalModuleAmd( ....
});
else if(typeof exports === 'object')
exports["kb"] = factory(require("knockout"), require("backbone"), require("underscore"), (function ....
else
root["kb"] = factory(root["ko"], root["Backbone"], root["_"], root["jQuery"]);
当我尝试将其导入 .ts 文件时,tsc 会产生错误:
import * as k from 'knockback/knockback';
TS2307: Build: Cannot find module 'knockback/knockback'.
除了编辑回击.js文件之外,我能做些什么来说服 tsc 导入此.js? 我正在使用打字稿 1.8。
当我尝试将其导入 .ts 文件时,tsc 会产生错误:
您可以非常轻松地使用类型定义文件
文件knockback.d.ts
declare module 'knockback/knockback' {
var foo: any;
export = foo;
}
仅供参考,对于最终尝试使用knockback的其他任何人.js通过Typescript,有一个预先存在的knockback.d.ts
文件可从DefinitelyTyped获得。 然而,现有的.d.ts不包括export
,所以不能与外部模块一起使用。 根据basarat的回答,我修改了.d.ts文件,如下所示:
1) 在末尾添加以下内容:
declare module "knockback" {
export = Knockback;
}
2)从末端取下declare var kb: Knockback.Static
。
3) 删除包装器interface Static extends Utils {
并将Static
接口内的所有内容移动到命名空间范围。 例:
老:
interface Static extends Utils {
ViewModel;
CollectionObservable;
collectionObservable(model?: Backbone.Collection<Backbone.Model>, options?: CollectionOptions): CollectionObservable;
observable(
/** the model to observe (can be null) */
model: Backbone.Model,
/** the create options. String is a single attribute name, Array is an array of attribute names. */
options: IObservableOptions,
/** the viewModel */
vm?: ViewModel): KnockoutObservable<any>;
...
}
新增功能:
function collectionObservable(model?: Backbone.Collection<Backbone.Model>, options?: CollectionOptions): CollectionObservable;
function observable(
/** the model to observe (can be null) */
model: Backbone.Model,
/** the create options. String is a single attribute name, Array is an array of attribute names. */
options: IObservableOptions,
/** the viewModel */
vm?: ViewModel): KnockoutObservable<any>;
...
这些更改后,用法如下所示:
import * as kb from 'knockback';
class MyViewModel extends kb.ViewModel {
public name: KnockoutObservable<string>;
constructor(model: Backbone.Model) {
super();
this.name = kb.observable(model, "name");
}
}
var model = new Backbone.Model({ name: "Hello World" });
var viewModel = new MyViewModel(model);
kb.applyBindings(viewModel, $("#kb_observable")[0]);