Open oushima opened 1 month ago
I ran into the same issue and realised we need to use LokiJS for web. It's in the docs:
The above will work on React Native (iOS/Android) and NodeJS. For the web, instead of
SQLiteAdapter
useLokiJSAdapter
I've created adapter.ts
and adapter.web.ts
:
// adapter.ts
import { type LokiAdapterOptions } from '@nozbe/watermelondb/adapters/lokijs'
import SQLiteAdapter from '@nozbe/watermelondb/adapters/sqlite'
import { SQLiteAdapterOptions } from '@nozbe/watermelondb/adapters/sqlite/type'
export const createAdapter = (
options: Pick<
SQLiteAdapterOptions,
// Accept only the options shared between SQLiteAdapterOptions and LokiAdapterOptions
Extract<keyof SQLiteAdapterOptions, keyof LokiAdapterOptions>
>,
) =>
new SQLiteAdapter({
jsi: true,
...options,
})
// adapter.web.ts
import LokiJSAdapter, {
type LokiAdapterOptions,
} from '@nozbe/watermelondb/adapters/lokijs'
import { type SQLiteAdapterOptions } from '@nozbe/watermelondb/adapters/sqlite/type'
export const createAdapter = (
options: Pick<
LokiAdapterOptions,
// Accept only the options shared between LokiAdapterOptions and SQLiteAdapterOptions
Extract<keyof LokiAdapterOptions, keyof SQLiteAdapterOptions>
>,
) =>
new LokiJSAdapter({
useWebWorker: false,
useIncrementalIndexedDB: true,
...options,
})
Use createAdapter
to create the appropriate adapter when creating the database instance:
// database.ts
import { Database } from '@nozbe/watermelondb'
import { Post } from './models/Post'
import { createAdapter } from './adapter' // <---- imports from adapter.web.ts on web
import { schema } from './schema'
export const database = new Database({
adapter: createAdapter({ schema }),
modelClasses: [Post],
})
Description
I am encountering an issue where the better_sqlite3.node module fails to load when using WatermelonDB in the web version of my React Native project. The mobile versions (iOS and Android) work fine. The error message suggests that the module cannot be found, although it exists in the expected directory.
Error Message
Steps to Reproduce
Install WatermelonDB and better-sqlite3 in a React Native project. Configure WatermelonDB with SQLiteAdapter. Run the project on the web.
Expected Behavior
The better_sqlite3.node module should load correctly, and the database should initialize without errors on the web version.
Observed Behavior
The web version fails to load the database, throwing an error indicating that the better_sqlite3.node module is an unknown named module. The iOS and Android versions work correctly.
Environment
The better_sqlite3.node file exists in the node_modules/better-sqlite3/build/Release directory. I've tried clearing the npm cache, reinstalling dependencies, rebuilding native modules, and ensuring the path resolution is correct. Other native modules load without issues.
Any guidance or suggestions to resolve this issue would be greatly appreciated.