多くのプロジェクトで使用できるようにしたい typescript で小さなライブラリを作成しました。一部のプロジェクトでは requirejs を使用し、他のプロジェクトでは使用しません。
AMDを使用してチェックする他のスクリプトがこれを行うのを見たことが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を使用し、Webサイトで説明されているようにロードすると機能しますが、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;
});
}