【问题标题】:How to properly split common dependencies with webpack4如何使用 webpack4 正确拆分常见依赖项
【发布时间】:2018-04-04 13:54:47
【问题描述】:

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

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

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

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

由于只有运行my-app 的页面需要lodash,我想在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

是否可以将所有“全局”依赖项放在core.bundle.js 中?

【问题讨论】:

标签: javascript webpack webpack-4


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2019-07-10
    相关资源
    最近更新 更多