【问题标题】:How to bundle each node_module as separate bundle in webpack?如何在 webpack 中将每个 node_module 捆绑为单独的包?
【发布时间】:2019-07-21 07:30:54
【问题描述】:

我有一个 React 项目,我们在其中使用了许多依赖项。我在关注this hackernoon post,其中作者提到如何将每个node_module 拆分为npm-package1.js...2.js 等单独的文件。

如何在我的 webpack 配置中实现它?我一直在尝试修改的当前 webpack 配置:

const prodWebpackConfig = {
  entry: {  },
  optimization: {
    runtimeChunk: 'single',
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendor',
          chunks: 'initial'
        }
      }
    }
  }
};

我正在运行这个文件,它总是在我的 dist 中生成应用程序、运行时、样式和 vendor.js。我无法将所有 NPM 包都视为捆绑包。如何实现这种配置?

【问题讨论】:

标签: webpack


【解决方案1】:

似乎指向作者要点的预期链接无法正常工作,但您仍然可以在 GitHub 上看到它们。这些示例的webpack.config.js 如下所示:


module.exports = {   entry: {
    main: path.resolve(__dirname, 'src/index.js'),
    ProductList: path.resolve(__dirname, 'src/ProductList/ProductList.js'),
    ProductPage: path.resolve(__dirname, 'src/ProductPage/ProductPage.js'),
    Icon: path.resolve(__dirname, 'src/Icon/Icon.js'),   },   output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash:8].js',   },   plugins: [
    new webpack.HashedModuleIdsPlugin(), // so that file hashes don't change unexpectedly   ],   optimization: {
    runtimeChunk: 'single',
    splitChunks: {
      chunks: 'all',
      maxInitialRequests: Infinity,
      minSize: 0,
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name(module) {
            // get the name. E.g. node_modules/packageName/not/this/part.js
            // or node_modules/packageName
            const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];

            // npm package names are URL-safe, but some servers don't like @ symbols
            return `npm.${packageName.replace('@', '')}`;
          },
        },
      },
    },   
  }, 
};

来源:https://gist.github.com/davidgilbertson/c9af3e583f95de03439adced007b47f1

【讨论】:

  • 感谢@jonrsharpe 的要点和编辑,我觉得这篇文章强调了许多为最终用户捆绑应用程序的最佳实践,只是想让你有同样的看法,这个让我少担心一件事
猜你喜欢
  • 2017-07-15
  • 1970-01-01
  • 2018-05-12
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
  • 1970-01-01
  • 2019-03-09
  • 1970-01-01
相关资源
最近更新 更多