Home > Web Front-end > JS Tutorial > es-toolkit, a Lodash alternative

es-toolkit, a Lodash alternative

Patricia Arquette
Release: 2024-11-15 04:55:02
Original
978 people have browsed it

Écrit par Rishi Purwar✏️

Si vous créez des applications JavaScript depuis un certain temps, vous avez probablement utilisé des bibliothèques d'utilitaires comme Lodash. Ces bibliothèques regorgent de fonctions utiles qui rendent le codage en JavaScript plus facile et plus efficace. Mais à mesure que votre projet se développe et que vous commencez à utiliser davantage de fonctions utilitaires, vous remarquerez peut-être que la taille de votre bundle commence également à augmenter.

Cela est particulièrement vrai lorsque vous comptez sur des bibliothèques lourdes comme Lodash, ce qui vous amène à vous demander s'il existe une meilleure alternative.

C'est là qu'intervient es-toolkit : une bibliothèque d'utilitaires JavaScript moderne et performante, légère et dotée d'un solide support TypeScript, ce qui en fait une excellente alternative aux bibliothèques populaires comme Lodash.

Voici les principales comparaisons entre es-toolkit et Lodash :

  • es-toolkit propose des fonctions utilitaires clés similaires à Lodash, couvrant des domaines tels que les fonctions, les tableaux, les objets, les chaînes, les mathématiques, les prédicats et les promesses
  • Les fonctions d'es-toolkit sont souvent plus rapides que celles de Lodash car elles utilisent des API JavaScript modernes dans leurs implémentations et TypeScript pour la vérification de type, réduisant ainsi le besoin de code défensif supplémentaire.
  • Les benchmarks de performances montrent que les fonctions d'es-toolkit surpassent leurs équivalents Lodash, parfois avec des marges significatives
  • Les fonctions d'es-toolkit ont des tailles de bundle nettement plus petites par rapport aux équivalents de Lodash, ce qui entraîne des temps de chargement plus rapides et de meilleures performances
  • es-toolkit répond aux problèmes de performances et de taille des bundles en exploitant les fonctionnalités JavaScript modernes et en évitant les interdépendances trouvées dans Lodash
  • Les fonctions d'es-toolkit sont pour la plupart autonomes, empêchant l'inclusion involontaire de code inutile, contrairement à Lodash où les fonctions utilitaires sont souvent interdépendantes

Entrons dans le vif du sujet de ces différences et voyons comment vous pouvez utiliser es-toolkit dans vos projets JavaScript.

Principales fonctionnalités de la boîte à outils es

Voici un aperçu rapide de ce que es-toolkit apporte à la table :

  • Functions including memoize to cache function results and debounce to limit how often a function is called
  • Arrays like uniq to filter out duplicates and difference to find what’s different between arrays
  • Tools for handling JavaScript objects, such as cloneDeep for deep cloning and flattenObject to transform nested objects into a flat structure
  • String manipulation tools, including kebabCase to convert strings to kebab-case
  • Math helpers like random for generating random numbers and round for rounding them off
  • Type guard functions like isNil to easily check for null or undefined values
  • Utilities for working with asynchronous code, like delay to pause execution for a bit

Performance and bundle size comparison

To truly understand the benefits of es-toolkit, let's compare its performance and bundle size to Lodash.

Performance

es-toolkit’s functions are often faster than Lodash’s because they use modern JavaScript APIs in their implementations. For example, es-toolkit’s omit function is about 11.8 times faster than lodash’s omit function.

Here’s a table comparing the performance of es-toolkit and lodash-es for various functions:

Function es-toolkit@0.0.1 lodash-es@4.17.21 Difference
omit 4,767,360 times 403,624 times 11.8×
pick 9,121,839 times 2,663,072 times 3.43×
differenceWith 9,291,897 times 4,275,222 times 2.17×
difference 10,436,101 times 5,155,631 times 2.02×
intersectionWith 8,074,722 times 3,814,479 times 2.12×
intersection 9,999,571 times 4,630,316 times 2.15×
unionBy 6,435,983 times 3,794,899 times 1.69×
union 5,059,209 times 4,771,400 times 1.06×
dropRightWhile 7,529,559 times 5,606,439 times 1.34×
groupBy 5,000,235 times 5,206,286 times 0.96×

バンドルサイズ

バンドルのサイズに関して言えば、es-toolkit は本当に優れています。バンドル サイズが小さいほど、Web アプリケーションの読み込みが速くなり、特に低速のネットワークでのパフォーマンスが向上します。

ここでは、es-toolkit と lodash-es のいくつかの一般的な関数のバンドル サイズの比較を示します。

Function es-toolkit@0.0.1 lodash-es@4.17.21 Difference
sample 88 bytes 2,000 bytes -95.6 percent
difference 91 bytes 3,190 bytes -97.2 percent
sum 152 bytes 413 bytes -63.2 percent
debounce 144 bytes 1,400 bytes -89.7 percent
throttle 110 bytes 1,460 bytes -92.5 percent
pick 657 bytes 3,860 bytes -83.0 percent
zip 797 bytes 1,790 bytes -55.5 percent

es-toolkit의 기능은 Lodash에 비해 훨씬 작습니다. 예를 들어, es-toolkit의 샘플 함수는 88바이트에 불과한 반면 Lodash의 동일한 함수는 2,000바이트로 거의 96% 더 작습니다!

JavaScript 앱에서 es-toolkit 사용

JavaScript 애플리케이션에서 es-toolkit을 사용하는 것이 얼마나 쉬운지 몇 가지 예를 살펴보겠습니다. 이 섹션에서는 es-toolkit이 디바운싱, 제한, 객체에서 특정 속성 선택, 배열에서 중복 항목 제거와 같은 일반적인 작업을 처리하는 방법을 살펴보겠습니다.

그러면 어떨까요? 작업을 더욱 쉽게 하기 위해 복제하고 즉시 실험을 시작할 수 있는 시작 코드 저장소를 GitHub에 정리했습니다. 시작하는 데 필요한 모든 것과 함께 우리가 다룰 모든 예제에 대한 HTML 및 CSS 코드를 찾을 수 있습니다. 여기에서 저장소를 확인하고 따라해보세요.

디바운스 예시

사용자가 다양한 주제에 대한 정보를 검색할 수 있는 웹사이트용 검색 기능을 구축한다고 가정해 보겠습니다.

사용자가 입력할 때마다 데이터를 가져오되 키 입력마다 요청을 보내지 않고 싶습니다. 그렇지 않으면 API 호출이 너무 많아질 수 있습니다. es-toolkit의 디바운스 기능이 유용한 곳이 바로 여기입니다.

작동 방식은 다음과 같습니다.

import { debounce } from "es-toolkit";

// a function that simulates an API call
function fetchData(query) {
  console.log(`Fetching data for: ${query}`);
}

// Using es-toolkit debounce function
const debouncedFetchData = debounce(fetchData, 1000);

document.getElementById("search-input").addEventListener("input", (event) => {
    const query = event.target.value;
    debouncedSearch(query);
});
Copy after login

아래 데모에서는 다섯 글자를 입력했지만 1초 동안 입력을 멈춘 후에만 fetchData 함수가 호출됩니다.

이렇게 하면 디바운스 기능을 사용하여 키를 누를 때마다 불필요한 API 요청을 방지할 수 있습니다.
es-toolkit, a Lodash alternative  

스로틀 예시

클릭하면 더 많은 게시물을 로드하는 버튼이 웹페이지에 있다고 가정해 보겠습니다. 버튼을 너무 빨리 클릭하는 경우 여러 API 호출을 방지하려면 es-toolkit의 조절 기능을 사용할 수 있습니다. 버튼을 여러 번 클릭하더라도 설정된 간격으로만 API 호출이 발생하도록 보장합니다.

사용 방법은 다음과 같습니다.

// Throttle Example
import { throttle } from "es-toolkit";

// Function to fetch posts from an API
async function fetchPosts() {
  console.log("Fetching new posts...");
  const response = await fetch("https://jsonplaceholder.typicode.com/posts");
  const posts = await response.json();
  console.log("Posts fetched:", posts);
}
// Create a throttled version of fetchPosts
const throttledFetchPosts = throttle(fetchPosts, 2000);

// Set up an event listener on the button
document.getElementById("fetch-more-posts").addEventListener("click", () => {
  console.log("button clicked");
  throttledFetchPosts();
});
Copy after login

이 예에서는 사용자가 "Fetch More Posts" 버튼을 빠르게 클릭하더라도 아래 데모와 같이 fetchPosts 기능이 2초에 한 번만 실행됩니다.
es-toolkit, a Lodash alternative  

예시 선택

자세한 사용자 프로필 데이터가 있지만 사용자 요약 구성 요소에 사용자 이름, 이메일, 연령과 같은 특정 속성만 표시하려고 한다고 가정해 보겠습니다. 선택 기능을 사용하면 이러한 속성을 쉽게 추출할 수 있습니다.

작동 방식을 보여주는 데모는 다음과 같습니다.

// Pick Example
import { pick } from "es-toolkit";

// dummy user data
const user = {
  id: 1,
  username: "johndoe",
  firstName: "John",
  lastName: "Doe",
  email: "john.doe@example.com",
  age: 30,
  address: {
    street: "123 Main St",
    city: "Anytown",
    country: "USA",
  },
  phoneNumber: "1234-5678",
};

// Use pick to select specific properties
const pickedUser = pick(user, ["username", "email", "age"]);

console.log("pickedUser", pickedUser)
Copy after login

이 예에서 pick 함수는 사용자 개체에서 사용자 이름, 이메일, 연령 속성을 추출합니다. 콘솔 로그는 다음을 출력합니다:

pickedUser: { username: 'johndoe', email: 'john.doe@example.com', age: 30 }
Copy after login

Uniq example

Imagine you’re running a blog where users can add tags to categorize their posts. You want to make sure that each tag only appears once. This is where the uniq function from es-toolkit is super useful. It helps you filter out duplicates from an array and get a list of unique tags.

Here’s a practical example:

>import { uniq } from "es-toolkit";

// Array of tags with some duplicates
const tags = [
  "javascript",
  "coding",
  "webdev",
  "programming",
  "javascript",
  "react",
  "nodejs",
  "coding",
  "html",
  "css",
  "webdev",
  "frontend",
];

// Use uniq to filter out duplicate tags
const uniqueTags = uniq(tags);

console.log("uniqueTags", uniqueTags);
Copy after login

In the above example, the uniq function removes duplicates from the tags array. The console log will output:

uniqueTags: ['javascript', 'coding', 'webdev', 'programming', 'react', 'nodejs', 'html', 'css', 'frontend']
Copy after login

How es-toolkit addresses performance and bundle size challenges

You might be curious about how es-toolkit tackles these challenges. Under the hood, es-toolkit leverages modern JavaScript APIs to deliver faster performance and significantly smaller bundle sizes.

On top of that, es-toolkit uses TypeScript, which helps cut out a lot of the extra defensive code that usually checks argument types at runtime. This not only makes the code run more efficiently but also minimizes any unnecessary overhead that can slow things down.

Another key difference is that Lodash utility functions are often interdependent, meaning that importing one function can drag in many others along with it. In contrast, es-toolkit functions are mostly standalone, which helps keep your bundle lightweight.

To really see the difference, you can use webpack-bundle-analyzer to visualize the size of your bundle. I've set everything up for you, so all you need to do is checkout to main branch and run npm i && npm run build from the root of the cloned repository, and it will open a page with all the details about your bundle.

The image below shows the bundle size when using es-toolkit. You can see that most es-toolkit functions are standalone, which results in smaller bundle sizes.

es-toolkit, a Lodash alternative  

Now, let's replace es-toolkit with lodash-es in the import statements from the examples above and run npm run build again to check the lodash-es bundle size.

The image below shows that Lodash functions are mostly interdependent, pulling in many other utilities when importing just one:

es-toolkit, a Lodash alternative  

Conclusion

es-toolkit can be a great alternative to utility libraries like Lodash, especially when performance and bundle size are key considerations. Its small bundle size, modern JavaScript features usage, and solid TypeScript support make it an excellent choice for developers.

I hope you found this exploration of es-toolkit helpful for your JavaScript projects, but don’t stop here! I encourage you to try out es-toolkit in your own applications and share your experiences with us in the comments below. Happy coding!


您是否添加新的 JS 庫來提高效能或建立新功能?如果他們反其道而行怎麼辦?

毫無疑問,前端變得越來越複雜。當您為應用程式新增新的 JavaScript 程式庫和其他依賴項時,您需要更多的可見性以確保您的使用者不會遇到未知問題。

LogRocket 是一個前端應用程式監控解決方案,可讓您重播 JavaScript 錯誤,就像它們發生在您自己的瀏覽器中一樣,以便您可以更有效地對錯誤做出反應。

es-toolkit, a Lodash alternative

LogRocket 可以與任何應用程式完美配合,無論框架如何,並且具有用於記錄來自 Redux、Vuex 和 @ngrx/store 的其他上下文的插件。您無需猜測問題發生的原因,而是可以匯總並報告問題發生時應用程式所處的狀態。 LogRocket 還監控您的應用程式的效能,報告客戶端 CPU 負載、客戶端記憶體使用量等指標。

自信地建造 — 開始免費監控。

The above is the detailed content of es-toolkit, a Lodash alternative. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template