iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 18
0
Modern Web

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

<18 - Plugins 小幫手 01> 自動產生 html 檔,並包含 bundle 後的檔案路徑 - html-webpack-plugin

  • 分享至 

  • twitterImage
  •  

在執行 webpack 進行 bundle 的過程中,若有使用 hash 碼的話,那麼在改變檔案程式的時候再進行 bundle 時,這些 hash 碼都會變得不一樣了,也就是會產生新的檔案,那麼我們可以藉由使用 html-webpack-plugin 產生 html 檔,讓我們快速地找到應該替換的相關檔案:

安裝 html-webpack-plugin

$ npm install html-webpack-plugin --save-dev

修改 webpack.config.js

新增以下程式:

…
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  …
  plugins: [
    …
    new HtmlWebpackPlugin()
  ]
}

這個時候再執行 webpack 指令,就可以看到自動產生了 ./dist/index.html 檔,內容如下:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>test here</title>
    <link href="app.bundle.css" rel="stylesheet"></head>
  <body>

    <script type="text/javascript" src="ea10be53549cccd55720.manifest.js"></script>
    <script type="text/javascript" src="05ef02be5a02714eab77.vendor.js"></script>
    <script type="text/javascript" src="818c5540c4a1c3cbc0eb.app.js"></script>
    <script type="text/javascript" src="7b53f76faf663d3f9746.another.js"></script>
  </body>
</html>

也就是會自動將 bundle 好的所有 css、js等相關路徑,會直接都帶出來。

chunks

這裡有一些關於 html-webpack-plugin configuration 的說明,而這裡我將簡單介紹 chunks 的使用。

很簡單,目前是將所有 bundle 後的路徑都會放入到所產生的 ./dist/index.html 檔中,而若需要只載入特定檔案的話,假設我只放入 vendor,修改 webpack.config.js 檔如下:

…
  plugins: [
    …
    new HtmlWebpackPlugin({
      chunks: ['vendor']
    })
  ]
…

那麼執行 webpack 指令後,所產生的 ./dist/index.html,就會只載入 vendor 的檔案,如下:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Webpack App</title>
  </head>
  <body>
    <script type="text/javascript" src="05ef02be5a02714eab77.vendor.js"></script>
  </body>
</html>

相反地,若將 chunks 改成 excludeChunks,就會將除了 vendor 的檔案,都載入。


好啦,我想這就是 html-webpack-plugin 的基本使用了。

明天想來談談 webpack-manifest-plugin,敬請期待。/images/emoticon/emoticon41.gif


上一篇
<17 - 再續心法 3> Code Splitting - Libraries
下一篇
<19 - Plugins 小幫手 02> 產生 bundle 後的 mapping 檔 - webpack-manifest-plugin
系列文
使用 webpack 模組化你的程式碼,讓人生更美好。30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言