入門Webpack(六)用一個實例說明代碼分割和懶加載

本文旨在用一個簡單的實例來講明代碼分割和懶加載。javascript

webpack提供了代碼分割和懶加載功能,關於這項功能,鄙人認爲代碼分割是前提,懶加載是結果,只有實現了代碼分割,才能懶加載。html

那麼如何才能實現代碼分割呢?須要在必定程度上按照懶加載的需求對原來的代碼進行修改。如何修改你須要知道下面的東東。java

代碼分割能夠採用webpack

  • webpack methods : require.ensure || require.include
  • ES2015 loader: System.import 基本廢棄變爲import || 動態import

require.ensure
官網中所require.ensure()已經被import( )所取代
這個方法接受四個參數git

var a = require('normal-dep');

if ( module.hot ) {
  require.ensure(['b'], function(require) {
    var c = require('c');

    // Do something special...
  });
}
  • dependencies: An array of strings declaring all modules required for
    the code in the callback to execute.
  • callback: A function that webpack will execute once the dependencies
    are loaded. An implementation of the require function is sent as a
    parameter to this function. The function body can use this to further
    require() modules it needs for execution.
  • errorCallback: A function that is executed when webpack fails to load
    the dependencies.
  • chunkName: A name given to the chunk created by this particular
    require.ensure(). By passing the same chunkName to various
    require.ensure() calls, we can combine their code into a single
    chunk, resulting in only one bundle that the browser must load.

看完了概念,下面讓咱們結合就具體的例子來看看代碼分割和懶加載。github

  1. 新建codeSplit文件夾
  2. npm init初始化
  3. npm install jsonp –save
  4. 新建app.js
  5. 新建webpack.config.json
  6. 當前目錄下新建src文件夾
  7. src文件夾下新建dom.js hot.js jsonp.js
  8. 主目錄下新建index.html

簡要說明:index.html只有一個button按鈕,點擊會發送ajax請求,請求qq音樂網站熱門搜索詞條。jsonp.js對第三方庫jsonp進行封裝,用jsonp是爲了實現跨域。點擊頁面button按鈕會發送ajax請求,並將請求到的數據處理後在控制檯打印。web

  • 代碼不分割
//webpack.config.js
var path = require('path')
module.exports = {
    entry: {
        app: './app.js'
    }
    output: {
        path: path.resovle('__dirname', './dist')
        publicPath: './dist/', //這一步不可少,不然代碼分割懶加載找不到相應文件
        filename: '[name].bundle.js'
    }
}

代碼不分割,打包後會生成app.bundle.js,html中引入該文件。在瀏覽器中打開會能夠看到加載了app.bundle.js,
這裏寫圖片描述
點擊button會發送ajax請求,在控制檯能夠看到信的網絡請求和須要打印的信息
這裏寫圖片描述
console.log 的信息
這裏寫圖片描述
上面這個例子是沒有進行代碼分割和懶加載的。ajax

  • 代碼分割npm

    代碼改寫分割後,能夠看到打包後生成app.bundle.js, dom.jsjson

    這裏寫圖片描述
    能夠看到初始頁面上加載的app.bundle.js由24.7kb變爲6kb,加載時間由8ms變爲7ms,複雜的項目中更能體現代碼分割和懶加載的優點。
    點擊頁面button按鈕,在控制檯的network中能夠看到先請求dom.bundle.js,而後發送ajax請求。
    這裏寫圖片描述
    本文用一個簡單的實例介紹了代碼分割和懶加載,import使用和require.ensure大同小異。咱們應該知道的是爲何須要代碼分割和懶加載,以及如何實現代碼分割和懶加載。

實例源碼:https://github.com/TyrionJYQ/Webpack

相關文章
相關標籤/搜索