vite+svelte+pouchdb:未捕获类型错误:类扩展值 [object Object] 不是构造函数或 null

Har*_*nan 7 pouchdb svelte vite

我正在尝试使用 Svelte + PouchDB 设置最低配置,并在浏览器中遇到上述错误。请参阅下面的步骤来重现该问题。

重现步骤:

  1. 使用 Svelte 模板创建一个简单的 Vite Scaffold 项目并验证它在浏览器中是否按预期工作
$ npm create vite@latest pouchdb-test -- --template svelte
$ cd pouchdb-test
$ npm install
$ npm run dev
Run Code Online (Sandbox Code Playgroud)
  1. 安装PouchDB(或pouchdb-browser,问题同样重现) $ npm install --save pouchdb

  2. 使用 PouchDB 创建数据库(下面的第 2 行和第 3 行是我添加的。其他行按原样存在。)

# 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>

Run Code Online (Sandbox Code Playgroud)
  1. 更新 vite.config.js (第 7 行是我添加的。其他的已经存在。)
# 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
});

Run Code Online (Sandbox Code Playgroud)
  1. 重建程序并在浏览器中打开应用程序(http://127.0.0.1:5173)。如果您检查控制台,则会抛出此异常:Uncaught TypeError: Class extends value [object Object] is not a constructor or null at index-browser.es.js:457:23

我无法理解为什么会出现此错误以及如何解决它。非常欢迎任何帮助或指示。

Har*_*nan 16

回答我自己的问题。2 个更改有助于解决该问题。

它是从 PouchDB 存储库中报告的类似问题中发现的https://github.com/pouchdb/pouchdb/issues/8607(因此积分归该问题的作者所有)

以下是变化:

  1. vite.config.js中更改“define: {global: {}}”以包含“window”
export default defineConfig({
    plugins: [svelte()],
    define: {global: "window"}   // <--- Add "window" here
});
Run Code Online (Sandbox Code Playgroud)
  1. 安装“事件”:npm install events

  • 这也适用于 vite+react+pouchdb。谢谢你! (4认同)