iT邦幫忙

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

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

<19 - Plugins 小幫手 02> 產生 bundle 後的 mapping 檔 - webpack-manifest-plugin

在開始之前,我想先將上一篇文章webpack.config.js 檔中有用到 html-webpack-plugin 的部份,先註解起來,如下:

…

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

…

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

…

為什麼呢?因為若自動產生了 ./dist/index.html,而在我原來專案資料夾中的 ./index.html,會有衝突,也就是當我執行 webpack-dev-server --open 的時候,用瀏覽器瀏覽 http://localhost:8080/,若 ./dist/index.html 檔存在的話,預設上是會使用這個檔的,但我想用的是 ./index.html,所以為了方便起見,我先將 html-webpack-plugin 註解起來了。這就是經驗啊…難怪我試好久都覺得有點怪怪的


回到正題,目前進行到這邊,其實在每次執行 webpack 指令的時候,都會產生類似以下的檔案:
http://ithelp.ithome.com.tw/upload/images/20161218/20069901gdDPDH1gdQ.png

這時我想要產生一個檔案,是能夠將原來的檔案,跟 bundle 後的檔案,是能跟對照的 mapping 檔,就可以透過 webpack-manifest-plugin 來達成,怎麼做呢?

安裝 webpack-manifest-plugin

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

修改 webpack.config.js

新增以下:

…

var ManifestPlugin = require('webpack-manifest-plugin');

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

這個時候,再執行 webpack 指令,就會自動產生 ./dist/manifest.json 檔案,內容如下:

{
  "70f2ba22aa302e129d79.0.js": "70f2ba22aa302e129d79.0.js",
  "another.js": "7b53f76faf663d3f9746.another.js",
  "app.css": "app.bundle.css",
  "app.js": "583c9c0b91328e29f4fa.app.js",
  "manifest.js": "961fc3b163b4f1301753.manifest.js",
  "vendor.js": "05ef02be5a02714eab77.vendor.js",
  "webpack.svg": "webpack-532a8eda5bf69bf78857fad01d675c44.svg"
}

這個檔案很適合用在後端來做解析,因為通常檔案有改變的時候,[hash] 碼都會變不一樣,所以就很適合拿這種檔案來做動態地解析。

預設產生後的檔名會是 manifest.json,若想要更改的話,只要在 webpack.config.js 將以下這行:

…
new ManifestPlugin()
…

改成:

…
new ManifestPlugin({
  fileName: 'custom-manifest.json'
})
…

custom-manifest.json 就是自訂的檔名,這樣即可完成 mapping 檔


明天想要來介紹另一個 clean-webpack-plugin,是能夠清除 bundle 後的 ./dist 資料夾,因為目前只要產生後的檔案,即使它已經舊了,其實都會留在 ./dist 資料夾,並不會自動清除,我希望能在每次執行 webpack 指令進行 bundle 的時候,在 ./dist 資料夾應該都是乾淨且會移除不必要的檔案。敬請期待。/images/emoticon/emoticon41.gif


上一篇
<18 - Plugins 小幫手 01> 自動產生 html 檔,並包含 bundle 後的檔案路徑 - html-webpack-plugin
下一篇
<20 - Plugins 小幫手 03> 清除 bundle 後的資料夾 - clean-webpack-plugin
系列文
使用 webpack 模組化你的程式碼,讓人生更美好。30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言