VSCode扩展开发中better-sqlite3构造函数报错求助
解决VSCode扩展中better-sqlite3实例化报错问题
问题背景
用TypeScript + Webpack开发VSCode扩展,集成better-sqlite3时,尝试在C:\Users\userName\AppData\Roaming\Code\User\globalStorage\目录创建数据库,触发报错:
TypeError: o.default is not a constructor
后续重装依赖后还出现过TypeError: Cannot read properties of undefined (reading 'indexOf'),移除try/catch后无报错,但仍无法正常创建数据库。已通过fs验证目录权限和项目配置正常。
相关代码与配置如下:
核心代码
import Database from 'better-sqlite3'; import * as fs from "fs"; import { DatabaseNames } from "./database-names.enum"; import { PersistenceRepository } from './persistence.repository'; export class BetterSqliteAdapter implements PersistenceRepository { private static instance: BetterSqliteAdapter | null = null; db: Database.Database | null = null; private constructor() { }; public static getInstance() { if (!this.instance) { this.instance = new BetterSqliteAdapter(); } return this.instance; } createDatabase(name: DatabaseNames, globalStoragePath: string): void { const dbPath = globalStoragePath + "\\" + name + ".db"; console.log('dbPath :>> ', dbPath); if (!fs.existsSync(globalStoragePath)) { throw new Error('Extension folder don\'t exist'); } if (!fs.existsSync(dbPath)) { try { this.db = new Database(dbPath); } catch (error) { console.log(`Error creating database: ${name}.db ... error: ${error}`); } } } }
tsconfig.json
{ "compilerOptions": { "module": "CommonJS", "target": "ES2020", "lib": ["ES2020", "DOM"], "sourceMap": true, "rootDir": "src", "strict": true , "jsx": "react", "esModuleInterop": true } }
解决方案
1. Webpack排除better-sqlite3打包
better-sqlite3是原生模块,Webpack打包会破坏其结构,需在webpack.config.js中将它标记为外部依赖,让Node.js运行时直接加载:
module.exports = { // 其他配置项... externals: { 'better-sqlite3': 'commonjs better-sqlite3' } };
2. 修正导入与实例化方式
启用esModuleInterop后仍可能存在导出兼容问题,尝试两种导入方式:
- 方式一:
import * as Database from 'better-sqlite3'; // 实例化时调用default this.db = new Database.default(dbPath);
- 方式二:直接使用CommonJS导入
const Database = require('better-sqlite3'); this.db = new Database(dbPath);
3. 针对Electron环境重新编译模块
VSCode基于Electron,better-sqlite3需适配该环境编译:
# 重新安装并从源码编译 npm install better-sqlite3 --build-from-source # 或用electron-rebuild强制编译 npx electron-rebuild -f -w better-sqlite3
4. 检查单例调用的this指向
确保createDatabase是通过实例调用,而非类直接调用:
// 正确调用示例 const adapter = BetterSqliteAdapter.getInstance(); adapter.createDatabase(DatabaseNames.XXX, globalStoragePath);
5. 移除try/catch定位真实报错
之前移除try/catch后无报错,说明异常被捕获但未完整输出。暂时去掉try/catch,运行后查看完整调用栈,精准定位问题行。
验证步骤
- 执行
npm clean-install清空并重装所有依赖 - 运行
npx electron-rebuild确保原生模块编译适配Electron - 调整Webpack配置与导入方式后,重新打包扩展
- 启动调试模式,检查目标目录是否生成数据库文件
内容的提问来源于stack exchange,提问作者vktop
相关产品推荐
相关产品推荐

