2016-04-27 60 views
0

例如,我有一些配置模塊:如何要求或模塊僅導入必要的出口具有的WebPack

exports.common = { 
 
\t cookieDomain: '.mydomain.dev', 
 
\t protocol: 'http', 
 
\t apiPort: 3030 
 
} 
 

 
exports.server { 
 
\t port: 8080 
 
}

在另一個模塊,我想只需要config.common對象,但避免來自config.server的代碼打入客戶端軟件包。這是可能的與webpack?

+0

這將成爲可能與webpack 2(目前在測試版),但只有ES2015語法,如果我沒有記錯。 – nils

+0

不是。如果你不需要它們在一起,不要把它們放在同一個模塊中。 – Bergi

回答

2

這被稱爲「樹搖」和will be a part of webpack 2。 無法雖然使用CommonJS的語法,你將需要使用ES2015模塊語法:

出口:

export const common = { 
    cookieDomain: '.mydomain.dev', 
    protocol: 'http', 
    apiPort: 3030 
}; 

export const server { 
    port: 8080 
}; 

導入:

import common from 'config'; 

common; // do something with common 
// server is not included in the bundle 

您可以使用當前安裝測試版版本號:

npm install [email protected] 

或者,你也可以h看看rollup.js,它支持這一點從開始(併產生更小的捆綁)。它也只支持ES2015語法。

+0

我安裝了webpack 2,但它不會搖動樹。我懷疑問題出在已安裝的預設或插件上。以下是我的.babelrc 「預設」:[「react」,「es2015」,「stage-0」,「es2015-loose」,「es2015-native-modules」], 「插件」:[ 「變換運行時」, 「變換裝飾遺」, 「變換級的屬性」 ], 「sourceMaps」:真, 「retainLines」:真 }' –

+0

刪除'es2015'和'ES2015 -loose',否則你的'import's會被轉換成'require();'s。 – nils

+0

我無法移除es2015,因爲nodejs上的serverside引發錯誤SyntaxError:意外的令牌導入 –