2016-08-30 28 views
1

我使用模塊方法將現有代碼轉換爲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 ?或者我可以嗎?

+0

如果您想要在打字稿中按需加​​載功能,則仍然需要加載器,因爲打字稿不提供模塊加載器的實現。 requirejs會這樣做,在'Optional Module Loading and Other Advanced Loading Scenarios'中甚至有一個requirejs的例子https://www.typescriptlang.org/docs/handbook/modules.html – artem

回答

0

你可以!我做的很多是在小文件中放入不同的功能,然後我有一個彙總文件重新導出它們。我認爲這也適用於你的使用情況?

文件1:

export let feature1 = ... 

文件2:

export let feature2 = ... 

文件3:

export namespace featureNamespace { 
    export { feature1 } from "./file1"; 
    export { feature2 } from "./file2"; 
} 

讓我知道,如果您有更多的問題,我會延長我的答案。

+0

你確定這可能嗎?我得到了「在命名空間中不允許導出聲明」的錯誤。 – Umair

+0

我在我的代碼中使用了這個確切的方法。奇怪。也許你不能導出名稱空間中的導入?我會盡快給您回覆。你使用哪個模塊加載器? –

+0

我正在使用requirejs – Umair