多入口

  1. const { resolve } = require('path');
  2. const HtmlWebpackPlugin = require('html-webpack-plugin');
  3. module.exports = {
  4. // 单入口
  5. // entry: './src/js/index.js',
  6. entry: {
  7. // 多入口:有一个入口,最终输出就有一个bundle(每一个入口文件,都相应有一个输入文件)
  8. index: './src/js/index.js',
  9. test: './src/js/test.js'
  10. },
  11. output: {
  12. // [name]:取文件名
  13. filename: 'js/[name].[contenthash:10].js',
  14. path: resolve(__dirname, 'build')
  15. },
  16. plugins: [
  17. new HtmlWebpackPlugin({
  18. template: './src/index.html',
  19. minify: {
  20. collapseWhitespace: true,
  21. removeComments: true
  22. }
  23. })
  24. ],
  25. mode: 'production'
  26. };

optimization

问题:若两个文件都引入了jquery,那么jquery会被打包进这两个文件 ===> 代码体积大
期望:两个文件的公共部分提取成独立部分

  1. // index.js
  2. import $ from 'jquery';
  3. // eslint-disable-next-line
  4. console.log($);
  1. // test.js
  2. import $ from 'jquery';
  3. // eslint-disable-next-line
  4. console.log($);
  1. const { resolve } = require('path');
  2. const HtmlWebpackPlugin = require('html-webpack-plugin');
  3. module.exports = {
  4. // 单入口
  5. // entry: './src/js/index.js',
  6. entry: {
  7. index: './src/js/index.js',
  8. test: './src/js/test.js'
  9. },
  10. output: {
  11. // [name]:取文件名
  12. filename: 'js/[name].[contenthash:10].js',
  13. path: resolve(__dirname, 'build')
  14. },
  15. plugins: [
  16. new HtmlWebpackPlugin({
  17. template: './src/index.html',
  18. minify: {
  19. collapseWhitespace: true,
  20. removeComments: true
  21. }
  22. })
  23. ],
  24. /**
  25. * 1. 可以将node_modules中代码单独打包一个chunk最终输出
  26. * 2. 自动分析多入口chunk中,有没有公共的文件。如果有会打包成单独一个chunk
  27. */
  28. optimization: {
  29. splitChunks: {
  30. chunks: 'all'
  31. }
  32. },
  33. mode: 'production'
  34. };

import()动态引入

import()动态引入返回的是一个Promise对象

// index.js
function sum(...args) {
  return args.reduce((p, c) => p + c, 0);
}

/**
 * 通过js代码,让某个文件被单独打包成一个chunk
 * import动态导入语法:能将某个文件单独打包
 */
import(/* webpackChunkName: 'test' */'./test')
  .then(({ mul, count }) => {
    // 文件加载成功~
    // eslint-disable-next-line
    console.log(mul(2, 5));
  })
  .catch(() => {
    // eslint-disable-next-line
    console.log('文件加载失败~');
  });

// eslint-disable-next-line
console.log(sum(1, 2, 3, 4));
const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  // 单入口
  entry: './src/js/index.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'
};