且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

webpack code splitting

更新时间:2022-08-12 10:36:23

代码拆分方案

1. Code Splitting - CSS
使用插件:npm i --save-dev extract-text-webpack-plugin

+var ExtractTextPlugin = require('extract-text-webpack-plugin');
 module.exports = {
    module: {
         rules: [{
             test: /\.css$/,
-            use: 'css-loader'
+            use: ExtractTextPlugin.extract({
+                use: 'css-loader'
+            })
         }]
     },
+    plugins: [
+        new ExtractTextPlugin('styles.css'),
+    ]
}

2. Code Splitting - Libraries
使用:CommonsChunkPlugin

var webpack = require('webpack');
var path = require('path');

module.exports = function() {
    return {
        entry: {
            main: './index.js',
            vendor: 'moment' 
            // 将第三方lib,单独打包到一个 bundle 中,充分利用浏览器基于内容的 hash 缓存策略
        },
        output: {
            filename: '[name].[chunkhash].js',
            path: path.resolve(__dirname, 'dist')
        },
        plugins: [
            new webpack.optimize.CommonsChunkPlugin({
                name: 'vendor',
                minChunks: function (module) {
                   // this assumes your vendor imports exist in the node_modules directory
                   return module.context && module.context.indexOf('node_modules') !== -1;
                }
            }),
            //CommonChunksPlugin will now extract all the common modules from vendor and main bundles
            new webpack.optimize.CommonsChunkPlugin({ 
                name: 'manifest' 
                //每次webpack工程时运行时代码发生改变,单独抽取运行时代码到清单文件中,
                // 所产生的开销通过浏览器缓存 Vendor 文件可以抵消回来
            })
        ]
    };
}

3. Code Splitting - Using import()
使用:

  1. npm install --save-dev babel-core babel-loader babel-plugin-syntax-dynamic-import babel-preset-es2015
  2. npm install --save moment
function determineDate() {
  import('moment')
    .then(moment => moment().format('LLLL'))
    .then(str => console.log(str))
    .catch(err => console.log('Failed to load moment', err));
}

determineDate();
  1. Usage with Babel and async / await
    To use ES2017 async /await with import()
    使用:npm install --save-dev babel-plugin-transform-async-to-generator babel-plugin-transform-regenerator babel-plugin-transform-runtime
async function determineDate() {
  const moment = await import('moment');
  return moment().format('LLLL');
}

determineDate().then(str => console.log(str));

webpack.config.js

module.exports = {
  entry: './index-es2017.js',
  output: {
    filename: 'dist.js',
  },
  module: {
    rules: [{
      test: /\.js$/,
      exclude: /(node_modules)/,
      use: [{
        loader: 'babel-loader',
        options: {
          presets: [['es2015', {modules: false}]],
          plugins: [
            'syntax-dynamic-import',
            'transform-async-to-generator',
            'transform-regenerator',
            'transform-runtime'
          ]
        }
      }]
    }]
  }
};

4. Code Splitting - Using require.ensure
webpack提出代码拆分的方案,可以将应用代码拆分为多个(chunk),每个块包含一个或多个模块,块可以按需异步加载
语法:
require.ensure(dependencies: String[], callback: function(require), chunkName: String)

require('./a');
require.ensure(["module-a"],function(require){
    var a = require("./b");
}, 'custom-chunk-name');
var a = require("./c");
// module-a.js 和 b.js 绑定在一起,并从主包中拆分。但是只执行 b.js 的内容。 module-a.js的内容只能提供,不能执行。 
// 要执行module-a.js,必须使用同步的方式来要求它,例如require('./module-a.js')来执行JavaScript。

通过require.ensure声明依赖module-a,module-a的实现及其依赖会被合并为一个单独的块,对应一个结果文件
当执行到require.ensure才去加载module-a所在的结果文件,并在module-a加载就绪后在执行传入的回调函数。(其中加载行为和回调函数执行时机控制由webpack实现。这对业务代码的侵入性极小)
在真实使用中,需要被拆分出来的可能是某个体积极大的第三方库(延后加载并使用),也可能是一个点击触发浮层的内部逻辑(除非触发条件得到满足,否则不需要加载执行),异步加载可以让我们以极小的代价,来极大地提升大规模单页面应用的初始加载速度


import 取代 require.ensure
Good news: Failure to load a chunk can be handled now because they are Promise based.
import 由于它是基于 Promise的,现在还不能加载 chunk

Caveat: require.ensure allows for easy chunk naming with the optional third argument, but import API doesn't offer that capability yet.
注意事项:require.ensure允许使用可选的第三个参数进行简单的块命名,但是 import API 还没有提供该功能。


模块热替换

webpack-dev-server --hot