在TypeScript中创建全局变量

时间:2017-01-05 15:18:42

标签: typescript

我一直在创建一个小型图书馆"我将用于Http请求。它是用TypeScript编写的,它有一个主要类Http。我希望能够在包含我的编译包之后在我的普通JavaScript中使用这个类,所以我正在思考如何让它在全球范围内可用。

我使用gulp-tsify作为编译器,它确实将我的TypeScript编译到es5包中,这很好,但是作为自调用函数在不同的范围内。当我在编译之后重写我的包(下面的代码)时,它工作正常,但是如何在不重写包脚本的情况下实现呢?

我的意思是......我编译的TypeScript如下所示:

(function e(t,n,r){ ... })(function(require, module, exports){
    ...
    // Somewhere here I've got var Http_1 = require('/...');
}, n, r)
// console.log(Http_1) -> undefined

当我宣布全局http(手动)...

var http;
(function e(t,n,r){
    ...
})(function(require, module, exports){
    ...
    // Somewhere here I've got var Http_1 = require('/...')
    http = Http_1;
    // or I can do this without the Http_1
    http = require('./classes/Http');
}, n, r)
// console.log(http) -> everything's fine

...用户可以使用http对象,但我希望它由编译器自动完成。

我正在考虑像TypeScript中的declare var http = Http;这样的东西,但我无法实现这一点,因为Initializers are not allowed in ambient contexts.有关如何做到这一点的任何想法?谢谢。

2 个答案:

答案 0 :(得分:1)

要添加浏览器全局,只需将项目附加到窗口对象即可。

window['Http'] = Http;

答案 1 :(得分:0)

使用特殊的全局语法:

declare global {
    interface Window {
        you: IAreCookingWithFire;
    }

    var you: IAreCookingWithFire;
}
相关问题