我使用模塊方法將現有代碼轉換爲typescript,但是,有一些代碼我不確定如何在打字稿中進行處理。假設你有這個Typescript模塊檢查項目是否已附加到名稱空間
featureNamespace = {
feature1: ...,
feature2: ...,
feature3: ...
};
function getFeature(feature: string) {
if (featureNamespace[feature]) {
return featureNamespace[feature];
}
throw `Feature '${feature}' has not been loaded`;
}
以前在featureNamespace
的特點是在單獨的文件,並通過requirejs被加載並附着到全局命名空間對象。
使用模塊化方法,我沒有可以使用的全局命名空間對象。我不能有,例如,
export module featureNamespace {
export let feature1 = ...
}
在一個文件中,並
export module featureNamespace {
export let feature2 = ...
}
在另一個文件
然後,不知何故,導入模塊featureNamespace
,並用它來檢查其功能已被附加到featureNamespace
?或者我可以嗎?
如果您想要在打字稿中按需加載功能,則仍然需要加載器,因爲打字稿不提供模塊加載器的實現。 requirejs會這樣做,在'Optional Module Loading and Other Advanced Loading Scenarios'中甚至有一個requirejs的例子https://www.typescriptlang.org/docs/handbook/modules.html – artem