我在 typescript 中创建了一个小型库,我希望能够在我的很多项目中使用它,一些项目使用 requirejs,而其他项目则没有。
我见过其他脚本这样做,它使用define
并检查 AMD,如果它们不存在,它会将对象附加到窗口对象或其他东西。
我想知道最好的方法是什么?如果可能的话,在打字稿中使用任何快捷方式或 w/e。
这是一个示例模块
export module Utilities {
//This is used to grab query string values from a javascript file
//pass the filename (without .js) into the constructor, then use
//GetValue(name) to find the query string values
export class QueryStringHelper {
names: string[] = [];
values: string[] = [];
constructor(public fileName: string) {
this.getQueryStringNameAndValues();
}
// GetValue(queryStringName: string) => number;
GetValue(queryStringName: string) {
var i = this.names.indexOf(queryStringName);
if (i == -1)
return undefined;
else {
if (this.values.length > i)
return this.values[i];
}
}
getQueryStringNameAndValues() {
var doc: HTMLDocument = document;
var scriptQuery: string = '';
// Look for the <script> node that loads this script to get its parameters.
// This starts looking at the end instead of just considering the last
// because deferred and async scripts run out of order.
// If the script is loaded twice, then this will run in reverse order.
// take from Google Prettify
for (var scripts = doc.scripts, i = scripts.length; --i >= 0;) {
var script = <HTMLScriptElement>scripts[i];
var match = script.src.match("^[^?#]*\\/" + this.fileName + "\\.js(\\?[^#]*)?(?:#.*)?$");
if (match) {
scriptQuery = match[1] || '';
// Remove the script from the DOM so that multiple runs at least run
// multiple times even if parameter sets are interpreted in reverse
// order.
script.parentNode.removeChild(script);
break;
}
}
var that = this;
scriptQuery.replace(
/[?&]([^&=]+)=([^&]+)/g,
function (_, name, value) {
value = decodeURIComponent(value);
name = decodeURIComponent(name);
that.names.push(name);
that.values.push(value);
return "";
});
}
}
}
当然,这在我使用 requireJS 时有效,并按照网站上的说明加载它,但如果我尝试在没有 requireJS 的情况下加载它,我会得到明显的define is not defined
异常。
我将如何使它...“可选”。
我确定这已经得到了回答,但我不知道要搜索什么(并且在命名问题时遇到了麻烦..随时编辑)
编辑示例
所以我知道这种方法有效,但这是做我正在寻找的正确方法吗?如果我这样做,我将来会遇到什么问题?
//i guess by default this is attached to the window object
//so it's automatically available to anything that just includes it
class TestClass {
constructor(public testValue: string) {
}
getTestValue(): string {
return this.testValue;
}
}
//attempt to support amd
if (typeof window['define'] === "function" && window['define']['amd']) {
window['define']("TestClass", [], function () {
return TestClass;
});
}
这产生了这个javascript
var TestClass = (function () {
function TestClass(testValue) {
this.testValue = testValue;
}
TestClass.prototype.getTestValue = function () {
return this.testValue;
};
return TestClass;
})();
if (typeof window['define'] === "function" && window['define']['amd']) {
window['define']("TestClass", [], function () {
return TestClass;
});
}