Reputation: 411
I am trying to setup a bare minimum configuration using Svelte + PouchDB and running into the above error in the browser. Please see below the steps to reproduce the issue.
Steps to reproduce:
$ npm create vite@latest pouchdb-test -- --template svelte
$ cd pouchdb-test
$ npm install
$ npm run dev
Install PouchDB (or pouchdb-browser, the issue is reproduced just the same)
$ npm install --save pouchdb
Create a DB using PouchDB (Lines 2 and 3 below were added by me. Other lines were present as-is.)
# src/lib/Counter.svelte
<script>
import PouchDB from "pouchdb"; // <--- or "pouchdb-browser" if that is installed
const db = new PouchDB('myDB'); // <--- Add this line too
let count = 0
const increment = () => {
count += 1
}
</script>
<button on:click={increment}>
count is {count}
</button>
# vite.config.js
import {defineConfig} from 'vite';
import {svelte} from '@sveltejs/vite-plugin-svelte';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [svelte()],
define: {global: {}} // <--- Add this line. If not present then this exception occurs:
// Uncaught ReferenceError: global is not defined
// at node_modules/immediate/lib/mutation.js (mutation.js:6:16)
// at __require (chunk-DFKQJ226.js?v=c3a35530:8:50)
// at node_modules/immediate/lib/index.js (index.js:5:3)
// at __require (chunk-DFKQJ226.js?v=c3a35530:8:50)
// at index-browser.es.js:1:23
});
I am unable to understand why this error occurs and how to solve it. Any help or pointers is most welcome.
Upvotes: 9
Views: 1501
Reputation: 955
I was trying to access pouchdb from a sveltekit +page.ts
loader, The above answer worked for me with a couple of tweaks.
Sveltekit was not able to assign window
to global
in the vite.config.ts
, so I omitted that step. I disabled ssr in sveltekit, but +page.ts
will run on both the server and the client even with ssr disabled. You'll start seeing errors about window
not being found.
I used ES6 dynamic imports to only import pouchdb-browser
when the loader is running in the client:
import { browser } from "$app/environment";
import type { PageLoad } from "./$types";
export const load: PageLoad = async ({ params }) => {
if (browser) {
const PouchDB = await import("pouchdb-browser");
// do pouch operations
return {
result
};
}
return {};
};
Upvotes: 1
Reputation: 411
Answering my own question. 2 changes helped resolve the issue.
It was found from a similar issue reported in the PouchDB repo https://github.com/pouchdb/pouchdb/issues/8607 (and so credits go to the author of the issue there)
Here are the changes:
export default defineConfig({
plugins: [svelte()],
define: {global: "window"} // <--- Add "window" here
});
npm install events
Upvotes: 22