使用 webpack, 專案開始時無論如何都先將 node_modules 移動到 chunk 中

Whien_Liou
Jul 10, 2017 · 3 min read

webpack 將我們所使用的任何開發程式與依賴模組打包成一塊,而 chunk 則可以將我們所指定的依賴模組透過相對應的設定額外打包,而在分離 chunk 中自己有些許心得記錄下來

版本都使用最新的 v3.1.0

  1. CommonsChunkPlugin

CommonChunkPlugin 是 webpack 中自帶的 plugin

const webpack = require('webpack');module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: '[name]-[hash].js',
chunkFilename: '[name].js'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin(string | object)
]
}

CommonChunkPlugin 在2.0後只能直接帶入字串或是一個物件,而兩種使用方式會有不同狀況

使用字串

plugins: [
new webpack.optimize.CommonsChunkPlugin('vendor')
]

如果只有使用字串會將 webpack 的 module 系統整個移動到 vendor.js 中

使用物件

使用物件可以搭配更多設定,尤其本篇要提出來的是 minChunks,這個 minChunks 可以帶一個方法,有個簡單技巧可以來選擇移動我們的 module

  • 利用 resource
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: (module, count) => {
return module.resource.indexOf('node_modules') > -1
}
})

物件中帶入一個 minChunks 方法,而 CommonsChunkPlugin 會自帶 module 跟 count 讓我們使用,上述例子則是利用 module 中帶的 resource 檔案位置有 ‘node_modules’ 關鍵字的檔案,這麼一來,就可以將我們的 node_modules 切割至 vendor chunk 中。

2. 有什麼好處

  • chunk 後,會將原本 webpack 自帶的 module 系統搬移到 chunk 中,就算沒有使用 node_modules 也減少了主要開發程式碼的檔案體積。
  • 將開發中程式與依賴程式做分離,再搭配 [hash] 可以降低瀏覽器每次更新後的檔案下載量,減少要求數。
  • 上述兩點是自己覺得專案一開始都應該先搬離的理由,而 chunk 還有更多的好處,會再整理成一篇

3. 如何引用

當切割成 chunk 後 webpack 會插入 webpackJsonp 系統,而 CommonsChunkPlugin 內部會將第一個切割的 chunk 插入 webpackJsonp,所以要務必記得將此 chunk 放在最上面,好讓後面的 chunks 可以使用。

<script src='./vendor.js'></script>
<script src='./bundle.js'></script>

結論

不論怎麼樣,能得到什麼好處,就先把 node_modules 搬移到 chunk 中吧!

前端壹兩三事

前端 ( Front End ) 新事物、解決問題、個人成長、收集與分享心得。

Whien_Liou

Written by

前端壹兩三事

前端 ( Front End ) 新事物、解決問題、個人成長、收集與分享心得。

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade