webpack code splitting

代碼拆分方案

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,單獨(dú)打包到一個(gè) bundle 中,充分利用瀏覽器基于內(nèi)容的 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工程時(shí)運(yùn)行時(shí)代碼發(fā)生改變,單獨(dú)抽取運(yùn)行時(shí)代碼到清單文件中,
                // 所產(chǎn)生的開銷通過瀏覽器緩存 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提出代碼拆分的方案,可以將應(yīng)用代碼拆分為多個(gè)(chunk),每個(gè)塊包含一個(gè)或多個(gè)模塊,塊可以按需異步加載
語法:
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 綁定在一起,并從主包中拆分。但是只執(zhí)行 b.js 的內(nèi)容。 module-a.js的內(nèi)容只能提供,不能執(zhí)行。 
// 要執(zhí)行module-a.js,必須使用同步的方式來要求它,例如require('./module-a.js')來執(zhí)行JavaScript。

通過require.ensure聲明依賴module-a,module-a的實(shí)現(xiàn)及其依賴會(huì)被合并為一個(gè)單獨(dú)的塊,對(duì)應(yīng)一個(gè)結(jié)果文件
當(dāng)執(zhí)行到require.ensure才去加載module-a所在的結(jié)果文件,并在module-a加載就緒后在執(zhí)行傳入的回調(diào)函數(shù)。(其中加載行為和回調(diào)函數(shù)執(zhí)行時(shí)機(jī)控制由webpack實(shí)現(xiàn)。這對(duì)業(yè)務(wù)代碼的侵入性極小)
在真實(shí)使用中,需要被拆分出來的可能是某個(gè)體積極大的第三方庫(延后加載并使用),也可能是一個(gè)點(diǎn)擊觸發(fā)浮層的內(nèi)部邏輯(除非觸發(fā)條件得到滿足,否則不需要加載執(zhí)行),異步加載可以讓我們以極小的代價(jià),來極大地提升大規(guī)模單頁面應(yīng)用的初始加載速度

**
import 取代 require.ensure
Good news: Failure to load a chunk can be handled now because they are Promise based.
import 由于它是基于 Promise的,現(xiàn)在還不能加載 chunk**

**Caveat: require.ensure allows for easy chunk naming with the optional third argument, but import API doesn't offer that capability yet.
注意事項(xiàng):require.ensure允許使用可選的第三個(gè)參數(shù)進(jìn)行簡單的塊命名,但是 import API 還沒有提供該功能。
**


模塊熱替換

webpack-dev-server --hot
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容