Webpack隐式供应商捆绑包和polyfill捆绑包。

5
我想要构建三个包:main.jsvendor.jspolyfill.js。其中,polyfill.js 文件应该包含在 polyfill.js 文件中定义的模块。vendor.js 文件应该通过提取从 npm (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 bundle,其中包含我在源文件中导入的所有node_modules。通过包括在polyfill.js文件中明确定义的所有模块来创建polyfill bundle。最后创建main bundle。

我已经尝试了许多webpack github存储库中的示例,但没有一个能帮助我实现上述功能

1个回答

1
我已经创建了一个Github仓库来展示工作示例。
以下是实现这种输出的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");
      }
    }),
  ]
}

你已经有这个配置的Webpack 4版本了吗?在WP4中遇到了困难。 - Marc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接