今天要來介紹另一個利器: html-loader ,讓我們來回顧一下 ./app/index.js 檔案吧,其中有一段是:

function appendImg(){
  var img = document.createElement('img');
  img.src = img_url;
  img.className = "tune_svg_width";
  return img;

還有印象嗎?其實很單純,它只是為了建立 <img src="路徑" class="tune_svg_width">,然後回傳 img,但會不會覺得很簡單的一行 html,卻要寫好幾行的js來產生呢?有沒有別的方式來取代呢?

有的,使用 html-loader,它會將 html 以字串的形式回傳。

又到了動手做的時間了/images/emoticon/emoticon31.gif

安裝 html-loader

$ npm install html-loader --save-dev
$ npm i -D html-loader

以上順帶一提,上面兩個語法是完全一樣結果的:

iinstall 的縮寫。 -D--save-dev 的縮寫。

建立 html 檔

建立 ./app/webpack_html/img_html.html,內容很簡單,僅一行:

<img src="../webpack.svg" class="tune_svg_width">

src 的路徑只要相對於目前的資料夾結構,指到正確的檔案即可,bundle 後會自動轉成正確的路徑。

此時只要再修改 ./app/index.js,僅列出新增的部份:

var img_str = require("html-loader!./webpack_html/img_html.html"); function appendImg(){ var img = document.createElement('img'); img.src = img_url; img.className = "tune_svg_width"; return img; return img_str;

appendImg() 函式將原內容都註解掉了,僅回傳 img_str,記得 html-loader 是會以字串形式回傳的。

document.body.appendChild(appendImg());
document.body.insertAdjacentHTML( 'beforeend', appendImg() );

在專案資料夾下,再執行以下指令:

$ webpack
$ webpack-dev-server --open

就一樣可以在 http://localhost:8080/webpack-dev-server/ 網址看到成功的畫面:

太棒了,我們成功將 html 抽離出來到另外的檔案了,不用再寫很長的 js,來產生簡易的 html 了。

html-loader 寫入 webpack.config.js

相信經過前幾天的練習,應該都知道如何寫入設定檔了,修改 webpack.config.js,增加一個 module.rules 規則:

module.exports = { module: { rules: [ test: /\.html$/, use: [ { loader: 'html-loader' }

修改 ./app/index.js,將:

var img_str = require("html-loader!./webpack_html/img_html.html");
var img_str = require("./webpack_html/img_html.html");

就大功告成啦,就可以再透過執行 webpack 指令,以及 webpack-dev-server --open 指令看到同樣的結果了~~/images/emoticon/emoticon58.gif

明天,繼續往下一個 loader 邁進吧,若你的專案中,有 json 檔,也可以將它納入你的模組當中,json-loader 即將登場,敬請其待。/images/emoticon/emoticon41.gif