首页 文章

在Typescript AMD模块中自动包含AMD deps?

提问于
浏览
8

有没有办法导入或注释Typescript模块,以便在生成与AMD兼容的模块时,外部AMD模块将自动作为依赖项包含在内?:

tsc --module AMD example.ts

我试图包括引用* .d.ts文件和导出声明语句:

///<reference path='./lib/knockout-2.2.d.ts' />

export declare var $;
export declare var _;

export module example {
    export class Example {
        // whatever
    }
}

但是生成的模块不包括以下内容:

define(["require", "exports"], function(require, exports) {
    (function (example) {
        var Example = (function () {
            function Example() { }
            return Example;
        })();
        example.Example = Example;        
    })(exports.example || (exports.example = {}));
    var example = exports.example;
})

真的想避免在这里创建“假”模块 .

这似乎是一个很好的解决方案,用法是允许直接导入AMD模块:

var $ = import('jquery'); // This is a requirejs/AMD module, not a typescript file.

但我不知道那是多么可行 .

编辑:

我也试过这里提到的方法:Import TypeScript module using only ambient definition for use in amd

import knockout = module("./lib/knockout-2.2.d.ts");
...

但得到这些编译器错误:

example.ts(1,32): The name '"./lib/knockout-2.2.d.ts"' does not exist in the current scope
example.ts(1,32): A module cannot be aliased to a non-module type

3 回答

  • 0

    在较新版本的TypeScript中,正确的方法是......

    示例(碰巧是jQuery)

    第1步:从NuGet下载定义文件(即jquery.typescript)

    第2步:这是代码(Visual Studio中不需要引用注释):

    /// <reference path="scripts/typings/jquery/jquery.d.ts" />
    
    import $ = require('jquery');
    
    export module foo {
        var elem = $('#myid');
    }
    

    生成的JavaScript:

    define(["require", "exports", 'jquery'], function(require, exports, $) {
        (function (foo) {
            var elem = $('#myid');
        })(exports.foo || (exports.foo = {}));
        var foo = exports.foo;
    });
    

    淘汰赛

    有些人在使用Knockout时遇到了麻烦...同样的技术适用于Knockout ......

    /// <reference path="scripts/typings/knockout/knockout.d.ts" />
    
    import ko = require('knockout');
    
    export module foo {
        var obs = ko.observable('example');
    }
    

    生成的JavaScript:

    define(["require", "exports", 'knockout'], function(require, exports, ko) {
        (function (foo) {
            var n = ko.observable('example');
        })(exports.foo || (exports.foo = {}));
        var foo = exports.foo;
    });
    
  • 4

    这个:

    declare module 'jquery' { export var n; };
    
    import $ = module('jquery');
    
    export module foo {
        var n = $.n;
    }
    

    将导致正确的 define 电话:

    define(["require", "exports", 'jquery'], ...
    

    请注意,如果您未在值位置使用导入的值(在此示例中为 $ )(而不是仅在类型位置中),编译器将优化该依赖项 .

  • 3

    Ryan的回答是有效的,除了新声明隐藏了三重注释的“.d.ts”文件中引用的类型 .

    要克服这一点,您可能想尝试更改声明,如下所示:

    declare module 'knockout' { export = knockout; }
    

    我没有用淘汰赛进行测试,但解决方案也应该可以解决 .

相关问题