如何在Webpack中从导出中排除供应商模块peerDependencies

How to exclude vendor module peerDependencies from export in Webpack?

本文关键字:排除 供应商 模块 peerDependencies Webpack      更新时间:2023-09-26

问题

在Webpack中导出捆绑包时,如何排除第三方模块的peerDependency?(不是第三方模块本身)

背景

我想在angular-material框架之上创建一个具有自定义组件的UIkit。使用Webpack,我可以将定制的组件和有角度的材料捆绑到类似uikit.js的东西中,然后稍后移植到其他应用程序。但是,我不想将angular模块本身包含在这个uikit.js中。

问题

Webpack似乎足够"聪明",注意到angular模块是angular-material模块的依赖项,因此会将angular模块和angular-material模块都导出到捆绑包中。可以使用config.externals: {'angular': 'angular'}new webpack.IgnorePlugin(/angular$/)来排除应用程序中明确需要的angular模块,但对于peerDependency(即angular-material内部需要的模块),它仍然会包括它。

那么,我怎么能将这个依赖第三方的模块排除在出口之外呢?

示例:

// app.js
var angular = require('angular');
var material = require('angular-material');
// ... other application logic    
// webpack.config.js
var webpack = require('webpack');
module.exports = {
  entry: {
    app: './app.js'
  },
  module: {
    loaders: [
      // some module loaders
    ]
  },
  // This only excludes the angular module require by the app, not the one require by the angular-material
  externals: {'angular': 'angular'},
  plugins: [
    // This is the same as externals, only the one required by app.js would be excluded
    new webpack.IgnorePlugin(/angular$/)
  ]
};

在webpack(版本4)配置中,我将供应商应用程序导出到供应商捆绑包和区块中,所有这些都是这样的:

entry: {
  app: './app.js',
  vendor: [ 'angular', 'angular-material', '...' ],
},
optimization: {
  splitChunks: {
    chunks: 'all',
  }
},

基本上,这表明将选择哪些块进行优化,all意味着即使在异步和非异步块之间也可以共享块。此外,如何构建模块以及如何处理依赖关系可以进一步优化块大小。

此外,您还可以提供一个函数,其返回值将指示是否包括每个区块:

module.exports = {
  //...
  optimization: {
    splitChunks: {
      chunks (chunk) {
        // exclude `my-excluded-chunk`
        return chunk.name !== 'my-excluded-chunk';
      }
    }
  }
};

这里有一个链接到webpack,解释splitChunks插件。