

最近工作中用到了nuxt,才發現,如果webpack學的6,nuxt基本不需要學習,沒什麼學習成本的,因此,這篇重新記錄下webpack4的一些基礎知識點,下一篇將會配置一個優化到極致的react腳手架,也希望大家能夠持續關注,配置webpack就是優化優化再優化,哈哈~
已經發布了webpack4的30個步驟打造優化到極致的react開發環境,如約而至,點選這裡
酒壯慫人膽,我學這個的辦法基本就分3步:
- 首先,將這些必要的配置,以及某些loader,某些外掛,像語文課文一樣默讀,並背誦(這一步最重要)
- 動手去實踐,去試錯
- 理解其原理
好了,正式開始
前言
Webpack可以看做是模組打包機:它做的事情是,分析你的專案結構,找到JavaScript模組以及其它的一些瀏覽器不能直接執行的擴充語言(Scss,TypeScript等),並將其打包為合適的格式以供瀏覽器使用。
WebPack和Grunt以及Gulp相比有什麼特性
其實Webpack和另外兩個並沒有太多的可比性,Gulp/Grunt是一種能夠優化前端的開發流程的工具,而WebPack是一種模組化的解決方案,不過Webpack的優點使得Webpack在很多場景下可以替代Gulp/Grunt類的工具。
- Entry:入口,Webpack 執行構建的第一步將從 Entry 開始,可抽象成輸入。
- Module:模組,在 Webpack 裡一切皆模組,一個模組對應著一個檔案。Webpack 會從配置的 Entry 開始遞迴找出所有依賴的模組。
- Chunk:程式碼塊,一個 Chunk 由多個模組組合而成,用於程式碼合併與分割。
- Loader:模組轉換器,用於把模組原內容按照需求轉換成新內容。
- Plugin:擴充套件外掛,在 Webpack 構建流程中的特定時機注入擴充套件邏輯來改變構建結果或做你想要的事情。
- Output:輸出結果,在 Webpack 經過一系列處理並得出最終想要的程式碼後輸出結果。
1. 從0開始配置結構
- 初始化專案結構

2. 配置webpack.config.js
- 在專案根目錄新建webpack.config.js

3. 配置開發伺服器

4. 打包js

5. 支援ES6,react,vue

6. 處理css,sass,以及css3屬性字首
處理css

動態解除安裝和載入CSS
style-loader為 css 物件提供了use()和unuse()兩種方法可以用來載入和解除安裝css
比如實現一個點選切換顏色的需求,修改index.js

處理sass

提取css檔案為單獨檔案

7.產出html

8. 處理引用的第三方庫,暴露全域性變數
webpack.ProvidePlugin引數是鍵值對形式,鍵就是我們專案中使用的變數名,值就是鍵所指向的庫

9. code splitting、懶載入(按需載入)
說白了就是在需要的時候在進行載入,比如一個場景,點選按鈕才載入某個js.

10. JS Tree Shaking

11. 圖片處理

12. Clean Plugin and Watch Mode
清空目錄,檔案有改動就重新打包

13. 區分環境變數

14. 開發模式與webpack-dev-server,proxy

到這裡基本就結束了,覺得有幫助,不妨點個贊,不足之處,還望斧正~