跳到主要內容
← 回到學習

學習 · 開發工具

lodash

目錄 · 4 個段落
  1. 01正確 import(tree-shake 友善)
  2. 02常用函式 + 原生替代
  3. 03debounce 範例(最常用)
  4. 04替代套件(2026 觀察)

Lodash 工具庫

TL;DR
Lodash 提供大量 utility 函式(陣列 / 物件 / debounce / throttle / 深拷貝)。2026 年觀察:多數 method 已被 現代 JS 原生 API 取代(structuredClone / Array.from(new Set()) / 等),只在需要 debounce / throttle 等非原生功能時用。

正確 import(tree-shake 友善)

// ❌ 不推薦:整個包進來(~70KB gzipped)
import _ from 'lodash';
_.debounce(fn, 300);
 
// ✅ 推薦:單一 method
import debounce from 'lodash/debounce';
 
// ✅ 或 ESM 版本(原生 tree-shake)
import { debounce } from 'lodash-es';
javascript

lodash-es vs lodash/{method}:

  • lodash-es — ES Modules,Vite / Rollup 自動 tree-shake
  • lodash/debounce — 手動指定單一 method,Webpack / 老 toolchain 也可以

都比 import _ from 'lodash' 小很多。


常用函式 + 原生替代

Lodash用途原生替代(2026)
debounce防抖(搜尋框)❌ 沒原生 → Lodash 仍最佳
throttle節流(滾動)❌ 沒原生 → Lodash 仍最佳
cloneDeep深拷貝✅ structuredClone(obj)
isEqual深比較❌ 沒原生 → Lodash 仍可
get安全取值✅ obj?.a?.b?.c ?? default
groupBy分組✅ Object.groupBy(arr, fn) (ES2024)
uniqBy去重⚠️ Array.from(new Map(arr.map(x => [x.id, x])).values())
flatten攤平✅ arr.flat()
flattenDeep完全攤平✅ arr.flat(Infinity)
chunk切塊❌ 沒原生 → Lodash
merge深合併❌ 沒原生( Object.assign 是淺合併)
2026 年保留 Lodash 的理由
  1. debounce / throttle(原生沒有)
  2. isEqual(深比較,原生 === 是 reference 相等)
  3. merge(深合併)
  4. chunk / partition / countBy / orderBy / sortBy 等 array helpers

純粹的 cloneDeep / get / flatten / groupBy / uniqBy 都已有原生 / 簡單寫法。


debounce 範例(最常用)

import debounce from 'lodash/debounce';
 
// 搜尋框 debounce
const handleSearch = debounce((query) => {
  fetch(`/api/search?q=${query}`);
}, 500);
 
// 取消 debounce(unmount 時)
handleSearch.cancel();
 
// 立即執行 + 取消 pending
handleSearch.flush();
javascript

React 用時要用 useMemo:

import { useMemo } from 'react';
import debounce from 'lodash/debounce';
 
function Search() {
  const handleSearch = useMemo(
    () => debounce((q) => fetch(`/api?q=${q}`), 500),
    [],
  );
 
  useEffect(() => () => handleSearch.cancel(), [handleSearch]);
 
  return <input onChange={(e) => handleSearch(e.target.value)} />;
}
tsx

每次 render 別重建 debounce(否則 timer 重置)。


替代套件(2026 觀察)

套件特色
lodash老牌,沒事用這個
remeda現代 TS-first,API 鏈式 + 型別安全
es-toolkit2024 出,號稱比 lodash 快 5x、體積小
ramdaFP-style,curry / pipe
// es-toolkit
import { debounce, cloneDeep, groupBy } from 'es-toolkit';
 
// remeda(pipe-friendly)
import { pipe, groupBy, map } from 'remeda';
const result = pipe(
  users,
  groupBy((u) => u.age),
  map((group) => group.length),
);
typescript

2026 年值得試 es-toolkit(在意 bundle size)或 remeda==(TS heavy 專案)。但 lodash 仍是社群最熟的選擇。

目錄