Skip to content

Webpack 5 配置与优化

笔记散乱,尚未整理

Lazyload and Prefetch

console.log('加载 index.js');

// webpackChunkName 可以指定打包出来的名称
// webpackPrefetch: 
//    false 按需异步加载
//    true 浏览器在空闲时间加载,真正需要时,加载其缓存
document.querySelector('#button').addEventListener('click', () => {
  import(
    /* webpackChunkName: 'add' */
    /* webpackPrefetch: true */
    './add.js'
  ).then(_m => {
    console.log('result:', _m.default(1, 2));
  })
});
  • index.js
import $ from 'jquery';
import react from 'react';
import reactDOM from 'react-dom';

console.log($);
console.log(react);
console.log(reactDOM);
  • webpack.dll.js,DLL 配置
const { resolve } = require('path');
const webpack = require('webpack');

module.exports = {
  entry: {
    jquery: ['jquery'],
    react: ['react', 'react-dom']
  },

  output: {
    filename: '[name].dll.js',
    path: resolve(__dirname, 'dll'),
    library: '[name]_dll_example'
  },

  plugins: [
    new webpack.NamedModulesPlugin(),

    new webpack.DllPlugin({
      name: '[name]_dll_example',
      format: true,
      path: resolve(__dirname, 'dll/manifest-[name].json')
    })
  ],

  mode: 'production' // development | production
};
  • webpack.config.js,主 APP 配置
const { resolve } = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const AddAssetHtmlWebpackPlugin = require('add-asset-html-webpack-plugin');

module.exports = {
  entry: resolve(__dirname, './src/index.js'),

  output: {
    filename: 'built.js',
    path: resolve(__dirname, 'build')
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: resolve(__dirname, './src/index.html')
    }),
    // 告诉 webpack 哪些库不参与打包
    new webpack.DllReferencePlugin({
      manifest: resolve(__dirname, 'dll/manifest-jquery.json')
    }),
    new webpack.DllReferencePlugin({
      manifest: resolve(__dirname, 'dll/manifest-react.json')
    }),
    new AddAssetHtmlWebpackPlugin([
      { filepath: resolve(__dirname, 'dll/jquery.dll.js') },
      { filepath: resolve(__dirname, 'dll/react.dll.js') }
    ])
  ],

  mode: 'production' // 'production' 'development'
};

Scope Hoisting

原理:分析出模块之间的依赖关系,尽可能将打散的模块合并到一个函数中,前提是不能造成代码冗余。 因此只有那些被引用了一次的模块才能被合并。

  • 支持 ES6 模块化语句,不支持 CJS
  • weppack mode = production 自动开启
  • 减少 __webpack_require__ 次数,运行速度提升:
    • 打包时,减少函数申明语句,代码体积更小
    • 运行时,创建的函数作用域更少,内存开销也随之变小