2017-05-01 98 views
5

我想建立三个捆绑:main.js,vendor.jspolyfill.jspolyfill.js文件应该包含在polyfill.js文件中定义的模块。应该通过提取从npm(node_modules)导入的所有依赖项来动态创建vendor.js文件。最后main.js应该包含除polyfillvendor模块之外的其他模块,这些模块实质上是我的应用程序代码。Webpack隐含供应商捆绑与polyfill捆绑

polyfill.js

import 'core-js/es7/reflect'; 
import 'zone.js/dist/zone'; 

main.js

import { NgModule, ApplicationRef } from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 
import { Store } from '@ngrx/store'; 

@NgModule([ 
    imports: [...] 
]) 
class AppModule { 
} 

我已经写了下面的WebPack配置,但总是得到以下错误:

"CommonsChunkPlugin: While running in normal mode it's not allowed to use a non-entry chunk (main)", 
    "CommonsChunkPlugin: While running in normal mode it's not allowed to use a non-entry chunk (vendor)" 

个webpack.config.prod.js

{ 
    entry: { 
    polyfill: './polyfill.ts', 
    main: './main.ts' 
    }, 
    output: { 
    publicPath: options.assetPath 
    }, 
    devtool: 'source-map', 
    plugins: [ 
    new webpack.optimize.CommonsChunkPlugin({ 
     name: 'vendor', 
     minChunks: function (module) { 
     const check = module.context && module.context.indexOf('node_modules') !== -1;   
     module.originalChunkNames = module.chunks.map(chunk=> chunk.name); 
     return check; 
     } 
    }), 
    new webpack.optimize.CommonsChunkPlugin({ 
     name: 'polyfill', 
     chunks: ['vendor'], 
     minChunks: ({ originalChunkNames }) => originalChunkNames.includes('polyfill'), 
    }), 
    new webpack.optimize.CommonsChunkPlugin({ 
     names: ['main', 'vendor', 'polyfill'], 
     minChunks: Infinity 
    }) 
    ] 
} 

在这里我想给做的是动态创建vendor束包括所有node_modules我导入我的源文件的内容。通过包含在polyfill.js文件中明确定义的所有模块来创建polyfill包。并最终main捆绑。

我试过很多例子来自的WebPack GitHub库,但没有他们的帮助我实现类似上述

回答

0

我创建了一个Github repository证明工作的例子。

下面是的WebPack结构的重要部分,以实现这种类型的输出:

{ 
    entry: { 
    polyfill: 'polyfill.ts', 
    main: 'main.ts' 
    }, 
    plugins: [ 
    new webpack.optimize.CommonsChunkPlugin({ 
     name: "vendor", 
     chunks: ["main"], 
     minChunks: function(module) { 
     const check = 
      module.context && module.context.indexOf("node_modules") !== -1; 
     module.originalChunkNames = module.chunks.map(chunk => chunk.name); 
     return check; 
     } 
    }), 
    new webpack.optimize.CommonsChunkPlugin({ 
     name: "polyfill", 
     chunks: ["vendor"], 
     minChunks: function({ originalChunkNames }) { 
     return originalChunkNames.includes("polyfill"); 
     } 
    }), 
    ] 
}