avatar
instagramthreads

Next.js 筆記 - Compiler with SWC

先來點 SWC 小知識

  • 可以理解為更快的 Babel
  • 20x faster than Babel on a single thread and 70x faster on four cores
  • 被 Next.js、Parcel、Deno、Vercel、ByteDance 等工具與公司採用
  • 冷知識
    • SWC 原作者是個 1997 的韓國小哥 DongYoon Kang (kdy)
    • Next.js 12 的文章中提到,目前 Vercel 已挖角了 SWC 作者 kdy 及 Parcel 核心貢獻者 Maia Teegarden,決心投資 Rust 生態系
  • 特性
    • Rust-based
    • 主要用來 compile JS/TS 成瀏覽器可識別的一般 JS
    • minification
    • bundling (稱作 swcpack,但還在開發中)
    • 可與 webpack 搭配 (swc-loader)
    • 可用來增進 Jest 效能 (@swc/jest)

Next.js Compiler Intro.

  • based on SWC platform,讓 Next.js 可編譯及 minify 你的 JS/TS code (取代了過往使用 Babel 及 Terser 這兩個工具)
  • 實測編譯效能比 Babel 提升 17x,在 Next.js v12 以上預設開啟
    • 當你的 repo 裡有 .babelrc 檔案,Next.js 會自動 fallback 使用 Babel,確保向後兼容
  • 選擇重構為 SWC 的原因
    • 擴展性:SWC 可直接被 Next.js 核心拿來當 Crate(Rust 中的 module 的意思),不需要對 SWC 本身做太多客製化修改
    • 效能:在轉過去 SWC 後,實測達到 3x fast refresh 及 5x fast build
    • WASM:支援 WASM,期待未來 Next.js 也能在瀏覽器之外的平台達到 native 般的效能
    • 社群:Rust 社群與生態性持續擴大中

Supported Features

  • Styled Components
    • 可取代 babel-plugin-styled-components ,但目前尚有一些 option 在開發中
  • Jest
    • 更簡易的 Jest 設定
      • 自動 mock .css, .module.css 與圖片
      • loading .envprocess.env
      • 忽略 node_modules 與 .next
      • 會參考 next.config.js 中的設定來看是否開啟 Jest 相關的實驗性選項
  • 提供 remove React properties 設定
    • 取代 babel-plugin-react-remove-properties ,像是把一些為了測試用的 data property 在 production build 時移除
  • 移除 console
    • 取代 babel-plugin-transform-remove-console ,也可客製不移除 console.error 之類的 (ref)
  • Minification
    • 從 v13 開始預設使用 SWC 取代 Terser,快了 7x
  • Module Transpilation
    • 主要是解決 monorepo 下的 local package 或外部 npm package (像是 lodash-es)轉譯,取代原本的 next-transpile-modules
  • Modularize Imports (doc)
    • v13.5 新優化 (ref),可以打開這個設定來自動在 production build 時去除掉沒有使用到的 modules

Reference