如何使用webpack4正确拆分公共依赖项

时间:2018-04-04 13:54:47

标签: javascript webpack webpack-4

我无法配置webpack4以正确捆绑共享依赖项。

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

第2页需要相同的,但也需要一个名为my-applodash的自定义JavaScript应用程序。

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

由于lodash只对运行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,但这两个包括jquery

是否有可能将所有&#34;全球&#34; core.bundle.js中的依赖关系?

1 个答案:

答案 0 :(得分:4)

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

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

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