除了匯出單一組態物件之外,還有其他幾種方式也能滿足其他需求。
最後你會發現需要在 webpack.config.js
中區分 開發 和 生產組建。有許多方法可以做到這一點。其中一種選項是從 webpack 組態匯出函式,而不是匯出物件。函式會使用兩個引數呼叫
argv
) 作為第二個參數。這說明傳遞給 webpack 的選項,其中包含 output-path
和 mode
等金鑰。-module.exports = {
+module.exports = function(env, argv) {
+ return {
+ mode: env.production ? 'production' : 'development',
+ devtool: env.production ? 'source-map' : 'eval',
plugins: [
new TerserPlugin({
terserOptions: {
+ compress: argv.mode === 'production' // only if `--mode production` was passed
}
})
]
+ };
};
Webpack 會執行組態檔匯出的函式,並等待 Promise 回傳。當您需要非同步載入組態變數時,這會很方便。
module.exports = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
entry: './app.js',
/* ... */
});
}, 5000);
});
};
您可以匯出多個組態(自 webpack 3.1.0 起支援多個函式),而不是匯出單一組態物件/函式。執行 webpack 時,會建置所有組態。例如,這對於 打包程式庫 以支援多個 目標(例如 AMD 和 CommonJS)很有用。
module.exports = [
{
output: {
filename: './dist-amd.js',
libraryTarget: 'amd',
},
name: 'amd',
entry: './app.js',
mode: 'production',
},
{
output: {
filename: './dist-commonjs.js',
libraryTarget: 'commonjs',
},
name: 'commonjs',
entry: './app.js',
mode: 'production',
},
];
如果您有一個組態依賴於另一個組態的輸出,您可以使用 dependencies
陣列指定相依性清單。
webpack.config.js
module.exports = [
{
name: 'client',
target: 'web',
// …
},
{
name: 'server',
target: 'node',
dependencies: ['client'],
},
];
如果您匯出多個組態,可以在組態陣列中使用 parallelism
選項,以指定並行編譯的最大編譯器數量。
數字
webpack.config.js
module.exports = [
{
//config-1
},
{
//config-2
},
];
module.exports.parallelism = 1;