1、准备

  1. import $ from 'jquery';
  2. function sum(...args) {
  3. return args.reduce((p, c) => p + c, 0);
  4. }
  5. // eslint-disable-next-line
  6. console.log(sum(1, 2, 3, 4));
  7. // eslint-disable-next-line
  8. console.log($);
  1. import $ from 'jquery';
  2. // eslint-disable-next-line
  3. console.log($);
  4. export function mul(x, y) {
  5. return x * y;
  6. }
  7. export function count(x, y) {
  8. return x - y;
  9. }
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>webpack</title>
  7. </head>
  8. <body>
  9. <h1>hello cache</h1>
  10. </body>
  11. </html>

1、未使用splitChunks代码分割时

1、webpack.config.js

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  // 单入口
  // entry: './src/js/index.js',
  entry: {
    index: './src/js/index.js',
    test: './src/js/test.js'
  },
  output: {
    // [name]:取文件名
    filename: 'js/[name].[contenthash:10].js',
    path: resolve(__dirname, 'build')
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      minify: {
        collapseWhitespace: true,
        removeComments: true
      }
    })
  ],
  mode: 'production'
};

2、结果

image.png
未使用splitChunks代码分割,导致文件很大,因为也引入了jquery。

2、使用splitChunks代码分割时

1、webpack.config.js

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  // 单入口
  // entry: './src/js/index.js',
  entry: {
    index: './src/js/index.js',
    test: './src/js/test.js'
  },
  output: {
    // [name]:取文件名
    filename: 'js/[name].[contenthash:10].js',
    path: resolve(__dirname, 'build')
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      minify: {
        collapseWhitespace: true,
        removeComments: true
      }
    })
  ],
  /*
    1. 可以将node_modules中代码单独打包一个chunk最终输出
    2. 自动分析多入口chunk中,有没有公共的文件。如果有会打包成单独一个chunk
  */
  optimization: {
    splitChunks: {
      chunks: 'all'
    }
  },
  mode: 'production'
};

2、结果

两个文件都引入了jquery,分割成3个文件,其中jquery单独生成一个chunk文件,其他文件也小了很多。
image.png