electric-sql / pglite

Lightweight Postgres packaged as WASM into a TypeScript library for the browser, Node.js, Bun and Deno
https://electric-sql.com
Apache License 2.0
4.76k stars 81 forks source link

Fix web worker syntax for webpack static analysis #103

Closed gregnr closed 1 week ago

gregnr commented 1 week ago

PGliteWorker doesn't currently work with webpack 5 (and Next.js) because webpack requires the worker to be loaded in a specific way. Instead of:

const WORKER_URL = new URL("./process.js", import.meta.url);
new Worker(WORKER_URL, { type: "module" });

webpack needs you to combine them into one line:

new Worker(new URL("./process.js", import.meta.url), { type: "module" });

I suspect this is because WORKER_URL could be dynamically created at runtime which breaks webpack's static analysis. And webpack needs to statically identify this at build time in order to perform special bundling on the worker script.

Created a quick fork @gregnr/pglite to test this and all appears to work now in Next 14:

import { PGliteWorker } from '@gregnr/pglite/worker'

const db = new PGliteWorker()

const result = await db.query('select 1');
// { rows: [...], fields: [...], affectedRows: 0 }
samwillis commented 1 week ago

Thanks @gregnr!