带有polyfill包的Webpack隐式供应商包

时间:2017-05-01 09:00:41

标签: webpack webpack-2

我想构建三个包:main.jsvendor.jspolyfill.jspolyfill.js文件应包含polyfill.js文件中定义的模块。应该通过提取从npm(vendor.js)导入的所有依赖项来动态创建node_modules文件。最后,main.js应包含polyfillvendor模块以外的模块,这些模块基本上都是我的应用代码。

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文件中明确定义的所有模块来创建polyfill.js包。最后的main捆绑。

我在webpack github repo中尝试过很多例子,但没有一个能帮助我实现上面提到的内容

1 个答案:

答案 0 :(得分:1)

我创建了一个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");
      }
    }),
  ]
}