Use PouchDB on a Vue 3 app with Vite
Fix the global-is-not-defined and process errors when using PouchDB in a Vue 3 + Vite application.
2 min read
Updated
Summarise this page with
your favorite AI assistant
PouchDB expects Node globals that Vite does not define in the browser, which usually shows up as global is not defined or a `process@@ error during the build. This note explains the two errors and the Vite configuration that resolves them. The configuration and error output are below.
When trying to use PouchDB on a web application built with the default Vite config, the build step failed with:
Error 1
text
Uncaught ReferenceError: global is not definedError 2
text
Uncaught Error: Module "events" has been externalized for browser compatibility and cannot be accessed in client code.This snippet shows how to fix this on index.html, package.json and vite.config.js
index.html.diff
diff
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<link rel="icon" href="/favicon.ico"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>MyApp</title>
</head>
<body>
<div id="app"></div>
+ <script>window.global = {}</script>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
package.json.diff
diff
{
"name": "myapp",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"pouchdb": "^7.2.2",
"pouchdb-find": "^7.2.2",
"vue": "^3.2.25"
},
"devDependencies": {
+ "events": "^3.3.0"
}
}
vite.config.js.diff
diff
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
],
+ optimizeDeps: {
+ include: [
+ 'events',
+ ],
+ },
});
Something wrong or want to discuss this article?
Get in touch