# Vite 2.9.5 ### 什麽是 Vite? :::warning Vite 是一個法文單字,意思為快速。**發音為 [vit]**。 ::: > Vite 是一種新的前端的建構工具(dev server + build-tool),能顯著提升前端開發體驗(Develop Experience)。 - **Dev serve** 基於 JS 原生 native ES modules(ESM) 快速建構。 - **Build command** 使用 rollup(ESM)優化建置靜態檔案。 #### 先來激起大家的興趣 > ✨ React 也可以用哦! ![](https://i.imgur.com/6BQGQDG.png) [state of JS 2021](https://2021.stateofjs.com/en-US/libraries/build-tools) [Create-react-app vs Vite + React](https://twitter.com/swyx/status/1290410811802804226) ### Vite 爲什麽那麽快? > 細談 Vite 核心思想架構 || Webpack | Vite | | -------- | -------- | -------- | | Dev serve | 打包(commonJS) > bundle.js > **run dev** | **run dev** (nodeJS koa) > *預建構依賴 + ESM(直接請求所需 module 及時編譯) | | **HMR** (Hot Module Replacement) | 需要把改動的 module 和相關依賴全部編譯 | 重新請求所需 module(利用瀏覽器 cache 緩存優化請求) -> **==速度將與專案大小無關==** || | Build | webpack build | rollup(ESM) | #### Dependencies & Source code > 如 Vite、Snowpack 這種非打包類型的構建工具,在開發環境啟動時需要啟動兩個 Server: - **一個用於頁面加載 (by Dependencies)。** ![](https://i.imgur.com/AlfX6Ww.png) :::info **Pre-bundles dependencies 預建構依賴** - **CommonJS & UMD -> ESM** (eg. React(commonJS)-> ESM) - **將轉換為 ESM 的許多内部模組建構為單個模組 -> 提高頁面加載性能** (eg. 載入 lodash 需要向瀏覽器發送 600+ 個 request ) - 預建構依賴機制指揮發生在 dev 階段,使用 **==[esbuild](https://esbuild.github.io/)==** 進行轉換成 ESM 的行爲。 <!-- 這是因為 esbuild 是使用 Go語言來編寫的,而在Go語言的核心是 採取併行性且有內存管理的機制,所以 esbuild 可以充分利用 CPU 來大量使用並行及內存機制,另外一個原因是 esbuild 在開發時是採取全部自己撰寫程式,無使用到 第三方模組,綜合以上原因,所以 速度優化上 可以這麼快! --> ::: - **一個用於 HMR 的 Websocket。** (當瀏覽器發出原生的 ESM 請求,Server 收到請求只需要編譯當前文件後返回給瀏覽器(出發 hot-reload、rerender 等事件),不需要管理依賴) :::info **靜態資源加載** 當請求的路徑符合 imageRE, mediaRE, fontsRE 或 JSON 格式,會被認為是一個靜態資源。靜態資源將處理成 ESM 返回。 ::: ![](https://i.imgur.com/Yktd6f9.png) ![](https://i.imgur.com/4eW5GZR.png) Vite also leverages HTTP headers to speed up full page reloads (again, let the browser do more work for us 👍 ### Vite 除了快還有... ![](https://i.imgur.com/EpSo1Bw.png) ### Webpack 掰掰 👋 ![](https://i.imgur.com/dYAvOT8.png) ![](https://i.imgur.com/RuavLo4.png) ![](https://i.imgur.com/iDyxMq6.png) JavaScript Module 支援度 ### 想要更瞭解 Vite - [官方網站](https://vitejs.dev/) - [MOPCON 2020 | vite: Make web dev fast again]() | [簡報](https://speakerdeck.com/kurotanshi/mopcon-2020-vite-make-web-dev-fast-again) - [Next generation frontend tooling with ViteJS Open Source Friday](https://www.youtube.com/watch?v=UJypSr8IhKY&ab_channel=GitHub) - [Tailwind 作者與 Evan You 對於 Vite 的對談 ](https://player.fm/series/series-1401837/ep-140-evan-you-reimagining-the-modern-dev-server-with-vite)