Reputation: 139
When I follow the instructions in the official pouchdb documentation and try to use pouchdb, it gives me an error saying:
ReferenceError: global is not defined
I am using Vite particularly in a Quasar Vue3 project
//package.json
"pouchdb": "^8.0.1",
"quasar": "^2.6.0",
"vue": "^3.0.0",
"vite": "^2.5.10",
code error import PouchDB from 'pouchdb'; const dbprueba = new PouchDB('kittens');
Apparently the error occurs because the "global" object is no longer exposed in Vite and pouchdb refers to that object.
Does anyone know what adjustments need to be made to the project to solve this problem?
Does anyone know what adjustments need to be made to the project to solve this problem?
Upvotes: 4
Views: 999
Reputation: 1659
In case anyone else runs across this, the package install bit doesn't matter. The actual problem is "window" window is missing on server side. The "less voodoo" method is to add this to your vite.config.ts (assuming you're using typescript):
optimizeDeps: {
esbuildOptions: {
define: {
global: 'window',
}
}
},
Just FYI this is a very common problem when using server side compilation that expect browser apis to be present. When building isomorphic javascript, you have to think "really hard" about the things you think will be available in the different runtimes and how to override/stub out alternatives.
Upvotes: 0
Reputation: 139
Searching the internet there is very little documentation about the error, but I managed to find a solution to it, and it is quite simple.
Step 1: We have to install an additional package called events
npm install events
line of package.json
"events": "^3.3.0",
Step 2: Search for the .html file, it is usually index.html and place a line of script there, I recommend putting it inside the at the end, before closing the head, however it also works when putting it as the first line of the "body"
<script>window.global = window</script>
what this line does is declare the "global" variable so that pouchDB uses it, given the problem that Vite does not declare that variable.
Step 3: Now we can import and use pouchdb, the following example creates a collection and then prints its information to the console.
import PouchDB from 'pouchdb';
const dbprueba = new PouchDB('kittens');
dbprueba.info().then(function (info) {
console.log(info);
});
Upvotes: 6