dexie vs idb
Web 开发中的 IndexedDB 库
dexieidb类似的npm包:

Web 开发中的 IndexedDB 库

Dexie 和 idb 是用于与 IndexedDB 进行交互的 JavaScript 库,旨在简化浏览器中存储大量结构化数据的过程。IndexedDB 是一种低级 API,允许在客户端存储大量数据,Dexie 和 idb 提供了更高层次的抽象,使得开发者可以更轻松地进行数据的存取和管理。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
dexie014,1093.09 MB5913 个月前Apache-2.0
idb07,27482.8 kB5710 个月前ISC

功能对比: dexie vs idb

API 设计

  • dexie:

    Dexie 提供了一个直观的 API,支持链式调用和丰富的查询功能,允许开发者以更简洁的方式进行复杂的数据库操作。它的设计使得数据的增删改查变得简单易懂,适合快速开发。

  • idb:

    idb 的 API 更接近原生 IndexedDB,提供了 Promise 风格的异步操作。虽然功能较为基础,但它的简洁性使得开发者可以灵活地进行自定义操作,适合需要直接操作数据库的场景。

查询能力

  • dexie:

    Dexie 支持复杂的查询和索引功能,允许开发者使用类似 SQL 的语法进行数据检索。它的查询能力强大,适合需要高效数据检索的应用。

  • idb:

    idb 提供基本的查询功能,支持索引,但在复杂查询方面不如 Dexie 灵活。适合简单的数据存取需求。

学习曲线

  • dexie:

    Dexie 的学习曲线相对较平缓,文档详细且易于理解,适合初学者快速上手。其丰富的功能和直观的 API 使得开发者可以迅速实现复杂的功能。

  • idb:

    idb 的学习曲线较陡峭,尤其是对不熟悉原生 IndexedDB 的开发者来说。虽然它提供了更大的灵活性,但需要更多的时间来掌握其用法。

性能

  • dexie:

    Dexie 在性能方面表现良好,尤其是在处理大量数据时。它的索引和查询优化使得数据操作更加高效,适合需要高性能的应用。

  • idb:

    idb 的性能与原生 IndexedDB 相当,适合对性能有严格要求的场景。由于其轻量级的特性,适合小型项目或简单的数据存取。

社区支持

  • dexie:

    Dexie 拥有活跃的社区和丰富的文档支持,开发者可以方便地找到解决方案和示例代码。

  • idb:

    idb 的社区相对较小,但由于其与原生 API 的紧密联系,开发者可以轻松找到相关的原生 IndexedDB 资源。

如何选择: dexie vs idb

  • dexie:

    选择 Dexie 如果你需要一个功能丰富且易于使用的库,提供强大的查询功能和链式调用。Dexie 适合需要复杂数据操作和更高层次抽象的应用。

  • idb:

    选择 idb 如果你更倾向于使用原生 API 的轻量级封装,并希望保持对 IndexedDB 的更大控制权。idb 提供了更接近底层的操作,适合需要细粒度控制的开发者。

dexie的README

Dexie.js

NPM Version Build Status Join our Discord

Dexie.js is a wrapper library for indexedDB - the standard database in the browser. https://dexie.org.

Why Dexie.js?

IndexedDB is the portable database for all browser engines. Dexie.js makes it fun and easy to work with.

But also:

  • Dexie.js is widely used by 100,000 of web sites, apps and other projects and supports all browsers, Electron for Desktop apps, Capacitor for iOS / Android apps and of course pure PWAs.
  • Dexie.js works around bugs in the IndexedDB implementations, giving a more stable user experience.
  • It's an easy step to make it sync.

Hello World (vanilla JS)

<!DOCTYPE html>
<html>
  <head>
    <script type="module">
      // Import Dexie
      import { Dexie } from 'https://unpkg.com/dexie/dist/modern/dexie.mjs';

      //
      // Declare Database
      //
      const db = new Dexie('FriendDatabase');
      db.version(1).stores({
        friends: '++id, age'
      });

      //
      // Play with it
      //
      try {
        await db.friends.add({ name: 'Alice', age: 21 });

        const youngFriends = await db.friends
            .where('age')
            .below(30)
            .toArray();

        alert(`My young friends: ${JSON.stringify(youngFriends)}`);
      } catch (e) {
        alert(`Oops: ${e}`);
      }
    </script>
  </head>
</html>

Yes, it's that simple. Read the docs to get into the details.

Hello World (legacy script tags)

<!DOCTYPE html>
<html>
  <head>
    <script src="https://unpkg.com/dexie/dist/dexie.js"></script>
    <script>

      //
      // Declare Database
      //
      const db = new Dexie('FriendDatabase');
      db.version(1).stores({
        friends: '++id, age'
      });

      //
      // Play with it
      //
      db.friends.add({ name: 'Alice', age: 21 }).then(() => {
        return db.friends
          .where('age')
          .below(30)
          .toArray();
      }).then(youngFriends => {
        alert (`My young friends: ${JSON.stringify(youngFriends)}`);
      }).catch (e => {
        alert(`Oops: ${e}`);
      });

    </script>
  </head>
</html>

Hello World (React + Typescript)

Real-world apps are often built using components in various frameworks. Here's a version of Hello World written for React and Typescript. There are also links below this sample to more tutorials for different frameworks...

import React from 'react';
import { Dexie, type EntityTable } from 'dexie';
import { useLiveQuery } from 'dexie-react-hooks';

// Typing for your entities (hint is to move this to its own module)
export interface Friend {
  id: number;
  name: string;
  age: number;
}

// Database declaration (move this to its own module also)
export const db = new Dexie('FriendDatabase') as Dexie & {
  friends: EntityTable<Friend, 'id'>;
};
db.version(1).stores({
  friends: '++id, age',
});

// Component:
export function MyDexieReactComponent() {
  const youngFriends = useLiveQuery(() =>
    db.friends
      .where('age')
      .below(30)
      .toArray()
  );

  return (
    <>
      <h3>My young friends</h3>
      <ul>
        {youngFriends?.map((f) => (
          <li key={f.id}>
            Name: {f.name}, Age: {f.age}
          </li>
        ))}
      </ul>
      <button
        onClick={() => {
          db.friends.add({ name: 'Alice', age: 21 });
        }}
      >
        Add another friend
      </button>
    </>
  );
}

Tutorials for React, Svelte, Vue, Angular and vanilla JS

API Reference

Samples

Performance

Dexie has kick-ass performance. Its bulk methods take advantage of a lesser-known feature in IndexedDB that makes it possible to store stuff without listening to every onsuccess event. This speeds up the performance to a maximum.

Supported operations

above(key): Collection;
aboveOrEqual(key): Collection;
add(item, key?): Promise;
and(filter: (x) => boolean): Collection;
anyOf(keys[]): Collection;
anyOfIgnoreCase(keys: string[]): Collection;
below(key): Collection;
belowOrEqual(key): Collection;
between(lower, upper, includeLower?, includeUpper?): Collection;
bulkAdd(items: Array): Promise;
bulkDelete(keys: Array): Promise;
bulkPut(items: Array): Promise;
clear(): Promise;
count(): Promise;
delete(key): Promise;
distinct(): Collection;
each(callback: (obj) => any): Promise;
eachKey(callback: (key) => any): Promise;
eachPrimaryKey(callback: (key) => any): Promise;
eachUniqueKey(callback: (key) => any): Promise;
equals(key): Collection;
equalsIgnoreCase(key): Collection;
filter(fn: (obj) => boolean): Collection;
first(): Promise;
get(key): Promise;
inAnyRange(ranges): Collection;
keys(): Promise;
last(): Promise;
limit(n: number): Collection;
modify(changeCallback: (obj: T, ctx:{value: T}) => void): Promise;
modify(changes: { [keyPath: string]: any } ): Promise;
noneOf(keys: Array): Collection;
notEqual(key): Collection;
offset(n: number): Collection;
or(indexOrPrimayKey: string): WhereClause;
orderBy(index: string): Collection;
primaryKeys(): Promise;
put(item: T, key?: Key): Promise;
reverse(): Collection;
sortBy(keyPath: string): Promise;
startsWith(key: string): Collection;
startsWithAnyOf(prefixes: string[]): Collection;
startsWithAnyOfIgnoreCase(prefixes: string[]): Collection;
startsWithIgnoreCase(key: string): Collection;
toArray(): Promise;
toCollection(): Collection;
uniqueKeys(): Promise;
until(filter: (value) => boolean, includeStopEntry?: boolean): Collection;
update(key: Key, changes: { [keyPath: string]: any }): Promise;

This is a mix of methods from WhereClause, Table and Collection. Dive into the API reference to see the details.

Dexie Cloud

Dexie Cloud is a commercial offering that can be used as an add-on to Dexie.js. It syncs a Dexie database with a server and enables developers to build apps without having to care about backend or database layer else than the frontend code with Dexie.js as the sole database layer.

Source for a sample Dexie Cloud app: Dexie Cloud To-do app

See the sample Dexie Cloud app in action: https://dexie.github.io/Dexie.js/dexie-cloud-todo-app/

Samples

https://dexie.org/docs/Samples

https://github.com/dexie/Dexie.js/tree/master/samples

Knowledge Base

https://dexie.org/docs/Questions-and-Answers

Website

https://dexie.org

Install via npm

npm install dexie

Download

For those who don't like package managers, here's the download links:

UMD (for legacy script includes as well as commonjs require):

https://unpkg.com/dexie@latest/dist/dexie.min.js

https://unpkg.com/dexie@latest/dist/dexie.min.js.map

Modern (ES module):

https://unpkg.com/dexie@latest/dist/modern/dexie.min.mjs

https://unpkg.com/dexie@latest/dist/modern/dexie.min.mjs.map

Typings:

https://unpkg.com/dexie@latest/dist/dexie.d.ts

Contributing

See CONTRIBUTING.md

Build

pnpm install
pnpm run build

Test

pnpm test

Watch

pnpm run watch

Browser testing via LAMDBATEST