这是两个淡化的示例文件。这就是目前它们作为 requirejs 模块的工作方式。我在我的要求配置中填充了 api.js 以将导出定义为 API。目标是这些将保持为单例。我正在尝试将它们转换为 TypeScript 等价物,但无法完全弄清楚如何将它们保持为单例并将它们传递给我现在所做的各种模块。
RequireJS 风格
api.js
(function (global) {
var API = global.API = {};
API.version = '0.0.1';
API.env = 'local';
API.header = '';
} (this));
auth.js
define([
'api',
], function (api) {
'use strict';
CommonAuth = {
maxExpiredAuthorizationRetries: 1,
getAuthorizationHeader: function () {
return api.header;
},
setAuthorizationHeader: function (val) {
api.header = val;
}
};
return CommonAuth;
}
);
TypeScript/AMD(requirejs) 风格
到目前为止,我有以下内容,但这显然不是我所追求的。
auth.ts
// don't know how to fake this without creating a valid api module. requirejs shim is what handles my export
import api = module("api");
export module Common {
class Auth {
public maxExpiredAuthorizationRetries: number;
constructor (maxExpiredAuthorizationRetries: number) {
this.maxExpiredAuthorizationRetries = maxExpiredAuthorizationRetries;
}
public getAuthorizationHeader(): string {
return api.header();
}
public setAuthorizationHeader(val: string): void {
api.header(val);
}
}
var auth = new Auth(1);
}
编译为auth.js ( tsc auth.ts --module amd
)
define(["require", "exports", "api"], function(require, exports, __api__) {
var api = __api__;
(function (Common) {
var Auth = (function () {
function Auth(maxExpiredAuthorizationRetries) {
this.maxExpiredAuthorizationRetries = maxExpiredAuthorizationRetries;
}
Auth.prototype.getAuthorizationHeader = function () {
return api.header();
};
Auth.prototype.setAuthorizationHeader = function (val) {
api.header(val);
};
return Auth;
})();
var auth = new Auth(1);
})(exports.Common || (exports.Common = {}));
})
更新:除了接受的答案之外,您还可以直接导出所有成员:
export var maxExpiredAuthorizationRetries: number = 1;
export function getAuthorizationHeader(): string { ...
export function setAuthorizationHeader(val: string): string {
然后import api = module('api');
可以简单地通过说来使用api.getAuthorizationHeader()
。