Typescript idiom to prevent duplicate modules included in a page
-
21-12-2019 - |
Question
Suppose I have a TypeScript module defined like:
module Foo {
export var now = new Date();
}
This gets transpiled to:
var Foo;
(function (Foo) {
Foo.now = new Date();
})(Foo || (Foo = {}));
If I were writing in pure JavaScript, I would have included something like:
var Foo;
(function (Foo) {
if (window.Foo) return; // <-- PREVENT DUPLICATES!
Foo.now = new Date();
})(Foo || (Foo = {}));
to ensure that this module gets defined only once even if the <script/>
gets included multiple times in a page. How do I achieve the same effect in TypeScript?
La solution 2
From this discussion on TS forums, I was able to come up with the following solution:
module window {
if (window.Foo) return;
export module Foo {
export var now = new Date()
}
}
This compiles to:
var window;
(function (window) {
if (window.Foo)
return;
(function (Foo) {
Foo.now = new Date();
})(window.Foo || (window.Foo = {}));
var Foo = window.Foo;
})(window || (window = {}));
Autres conseils
If you are writing your whole program in TypeScript, the compiler checks this for you...
module Foo {
export class X {
go() {
alert('First');
}
}
}
module Foo {
export class X { // Duplicate identifier X
go() {
alert('Second');
}
}
}
If you can, using external modules along with a module loader (RequireJS for example) ensures that non of your code needs to be added to the global scope, so it wouldn't conflict...
import foo = require('./foo');
export class Y {
go() {
return new foo.X();
}
}
Compiles to:
define(["require", "exports", './foo'], function(require, exports, foo) {
var Y = (function () {
function Y() {
}
Y.prototype.go = function () {
return new foo.X();
};
return Y;
})();
exports.Y = Y;
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow