首页 文章

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

提问于
浏览
5

我想构建三个包: main.jsvendor.jspolyfill.js . polyfill.js 文件应包含 polyfill.js 文件中定义的模块 . 应通过提取从npm( node_modules )导入的所有依赖项来动态创建 vendor.js 文件 . 最后 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.js 文件中明确定义的所有模块来创建 polyfill 包 . 最后的 main 捆绑 .

I've tried lots of example from webpack github repo but none of them helped me to achieve something like above mentioned

1 回答

  • 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");
          }
        }),
      ]
    }
    

相关问题