Typescript可以导入W​​ebpack UMD吗?

时间:2016-03-02 04:56:54

标签: typescript webpack knockback.js

使用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'.

除了编辑knockback.js文件之外,还有什么我可以做的,说服tsc导入这个.js?我使用的是Typescript 1.8。

2 个答案:

答案 0 :(得分:4)

  

当我尝试将其导入.ts文件时,tsc会产生错误:

您可以非常轻松地使用类型定义文件

档案knockback.d.ts

declare module 'knockback/knockback' {
    var foo: any;
    export = foo;
}

答案 1 :(得分:0)

仅供参考,对于那些最终试图通过Typescript使用knockback.js的人来说,DefinitelyTyped提供了一个预先存在的Error in .startAsciiWriting(x, filename, ...) : x has unequal horizontal and vertical resolutions. Such data cannot be stored in arc-ascii format 文件。但是,现有的.d.ts不包含knockback.d.ts,因此不能与外部模块一起使用。基于 basarat' 答案,我修改了.d.ts文件,如下所示:

1)将以下内容添加到最后:

export

2)从最后删除declare module "knockback" { export = Knockback; }

3)删除declare var kb: Knockback.Static包装器并将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>;
    ...