如何使用 webpack4 正确拆分常见依赖项

How to properly split common dependencies with webpack4

我在配置 webpack4 以正确捆绑共享依赖项时遇到困难。

我的应用程序中有两个页面(Page1 和 Page2)。两者都需要 bootstrapjquery 以及名为 core.

的自定义 JavaScript 应用程序

第 2 页需要相同但还需要一个名为 my-app 的自定义 JavaScript 应用程序以及 lodash.

由于我的 core 应用程序将包含在所有页面中,我希望将 jquerybootstrap 放在同一个包中。

因为 lodash 只需要页面 运行ning my-app,我想将该依赖项包含在 my-app 包中。

所以我这样设置我的应用程序:

webpack.config.js

const path = require('path');
const webpack = require('webpack');


module.exports = {
  entry: {
    'core': './src/core/index.js',
    'my-app': './src/my-app/index.js'
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  resolve: {
    alias: {
      jquery: 'jquery/src/jquery',
    }
  },
  plugins: [
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
    }),
  ],
  mode: 'development',
}

page1.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page1</title>

    <script src="dist/core.bundle.js"></script>
  </head>
  <body>
    <h1>Page1</h1>
    <span id="test"></span>
  </body>
  <script>
    $(document).ready(function() {
      $('#test').text('jQuery Works!');
    });
  </script>
</html>

page2.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page1</title>

    <script src="dist/core.bundle.js"></script>
    <script src="dist/my-app.bundle.js"></script>

  </head>
  <body>
    <h1>Page2</h1>
    <span id="test"></span>
  </body>
  <script>
    $(document).ready(function() {
      $('#test').text('jQuery Works!');
    });
  </script>
</html>

(完整项目:https://github.com/LondonAppDev/webpack-split-example

当我 运行 npx webpack 时,它会创建 core.bundle.jsmy-app.bundle.js,但是 both 其中包括 jquery.

是否可以将所有 "global" 依赖项都放在 core.bundle.js 中?

这里只需要记住一件事,使用 webpack 4,您不会将供应商脚本作为入口添加到您的 webpack.config,而是将真正的入口脚本添加到您的应用程序中。 WP 将使用默认设置为您的应用创建优化的捆绑输出。

您必须将供应商缓存组添加到您的配置中,以便将 jQuery, Lodash, Bootstrap,Popper 提取到单独的包中:

 optimization: {
    splitChunks: {
      cacheGroups: {       
        vendor: {
          test: /node_modules/,
          name: "vendor",
          chunks: "all", 
          enforce: true
        }
      }
    }
  },