TypeScript可以导入Webpack UMD吗?

6
使用TypeScript,是否可以以某种方式导入已由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'.

除了编辑knockback.js文件之外,有没有其他办法让tsc导入这个.js文件呢?我正在使用Typescript 1.8。

2个回答

4
当我尝试将这个导入到 .ts 文件中时,tsc 会产生一个错误:
你可以很容易地使用类型定义文件:
文件 knockback.d.ts
declare module 'knockback/knockback' {
    var foo: any;
    export = foo;
}

0

顺便提一下,对于任何试图通过TypeScript使用knockback.js的人,可以在DefinitelyTyped上找到一个现成的knockback.d.ts文件。然而,现有的.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]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接