pouchdb: Module build for browser breaks when built with vite
Issue
When including PouchDB in vite projects, vite removes all Node modules when building for the browser. During the bundling phase, vite outputs externalized node built-in "events" to empty module
and in the browser I get the error Module "events" has been externalized for browser compatibility and cannot be accessed in client code.
The workaround explained in #8130 does not work any more.
My suggestion for a solution would be to add the node-polyfills rollup plugin when building the browser es6 module. This will replace the “events” builtin with functionally identical code. I could try to provide a patch.
Info
- Environment: browser
- Build System: Vite/Rollup
Reproduce
Create a new vite app and add the line import PouchDB from 'pouchdb-browser'
to the file main.js
npm init vite-app testApp
cd testApp
npm i && npm i pouchdb-browser
npm run dev
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 7
- Comments: 19
Commits related to this issue
- Integrate RxDB Changes to app.html to resolve: `global is not defined` and `process is not defined` and `Cannot read properties of undefined (reading 'NODE_DEBUG')` Changes to svelte.config.ts to re... — committed to TechplexEngineer/bionic-scouting by TechplexEngineer 3 years ago
- assigned some window stuff https://github.com/pouchdb/pouchdb/issues/8266 — committed to AlexErrant/Pentive by AlexErrant 3 years ago
I got this working with two steps:
global
towindow
invite.config.js
:2:
npm install events
No other config necessary.
I haven’t worked with electron for quite a while, but for my most recent (small) project I used
vite-plugin-html
to work around the problem along with adding two lines inindex.html
In vite.config.ts
In index.html’s <head> tag
The reason why there’s two definitions of
window.process
is because of a difference in how it’s built/bundled depending on if you’re running dev or build. Hope this works for your case @hcker2000Here is my setup that I got working with vite@2.0.0-beta.52 (the current version is .53, but is totally broken). My apologies if it’s not relevant for this issue.
I didn’t run into the issue with events being undefined, but that was solved for me in #8130.
Edit: Added
window.global = window;
to main.jsI have the same problem, your answer works, thx.
Great @jbjorge please let me know if you need any assistance. I love Couchdb - Cloudant, Pouchdb and Vue. They are my main tools.
As you stated, hope the author of the issue could find the information you have shared useful.