iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 15
1
Modern Web

使用 webpack 模組化你的程式碼,讓人生更美好。系列 第 15

<15 - 再續心法 1> Code Splitting - Using Require

今天要來探討如何使用 require.ensure() 做程式碼分離,直接開始動手做/images/emoticon/emoticon31.gif

split point

為了方便測試,先建立全新的 ./index2.html 檔,內容很單純,只有這樣:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Webpack demo</title>
  </head>
  <body>
    <script src="dist/another.js" type="text/javascript"></script>
  </body>
</html>

然後接下來建立 ./app/another.js 檔案,內容很簡單,也只有這樣:

require.ensure([], function(require){
    require('./a2.js');
});

它的運作原理:在後續 bundle 的時候,會產生 ./dist/another.js 檔,以及 a2.js 會被 bundle 到另外一個檔案。而當有頁面(index2.html)在載入 another.js 檔的時候,會以非同步的方式,載入 a2.js 被 bundle 的那個檔案。 以下讓我們來實驗看看:

建立 ./app/a2.js,內容只有這樣:

console.log("I am a2 file.");

再修改 webpack.config.js 檔,entry 新增一行:

…
entry: {
  …
  another: './app/another.js',
  …
},
…

再執行 webpack 指令。

好,以上 bundle 的結果,其實會產生兩個檔案:./dist/another.js 以及 ./dist/0.js 檔案,而 index2.html 在載入 dist/another.js 的時候,會在 <head> 區段建立以 非同步 方式載入 ./dist/0.js 檔的 <script> 語法。

再執行 webpack-dev-server --open 來看看畫面結果:

第一張圖,瀏覽器的 console 畫面,有印出訊息(I am a2 file.):
http://ithelp.ithome.com.tw/upload/images/20161214/20069901QgzWHZWdsl.png

第二張圖,程式碼中可看到 0.js 是以 async 非同步方式來載入。
http://ithelp.ithome.com.tw/upload/images/20161214/20069901lwZROyNov7.png

Dependency

讓我們回到 ./app/another.js 檔的程式:

require.ensure([], function(require){
    require('./a2.js');
});

將它改成:

require.ensure(['./a1.js'], function(require){
    require('./a2.js');
});

這樣的原理是:除了 ./app/another.js 會被 bundle 到另外的檔案之外,a2.js 會相依於 a1.js,故會將 a1.jsa2.js 這兩個檔案 bundle 在同一個檔案,以此例來講會是./dist/0.js 檔,所以當頁面在載入 another.js 的時候,會以非同步的方式載入 0.js ,但只有 a2.js 會執行。若你希望a1.js 也要執行的話,只要在 ./app/another.js 檔的最上方再加上 require('./a1.js') 即可。

故要再建立 ./app/a1.js 檔,內容一樣只有一行:

console.log("I am a1 file.");

index2.html 內容不變,然後再執行 webpackwebpack-dev-server --open 就完成囉。相關的官網解說也可以在此看

大家可試著練習看看,實際狀況就依照專案來搭配適合的方式使用。/images/emoticon/emoticon41.gif


上一篇
<14 - 溫故知新 2> 附上目前的程式碼,即將進入 Code Splitting 心法
下一篇
<16 - 再續心法 2> Code Splitting - CSS
系列文
使用 webpack 模組化你的程式碼,讓人生更美好。30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言