如何在 webpack 中将每个 node_module 捆绑为单独的捆绑包?

Rah*_*ngh 2 webpack

我有一个 React 项目,我们在其中使用了许多依赖项。我正在关注这篇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'
        }
      }
    }
  }
};
Run Code Online (Sandbox Code Playgroud)

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

jon*_*rpe 6

看起来指向作者 Gists 的预期链接无法正常工作,但您仍然可以在 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('@', '')}`;
          },
        },
      },
    },   
  }, 
};
Run Code Online (Sandbox Code Playgroud)

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