Skip to content

Electron 集成 better-sqlite3,以及安装时遇到的问题

安装过程

1. 环境介绍

  • Electron: 28.3.1
  • Electron-rebuild: 3.6.0
  • Nodejs: 18.18.2
  • Python: 3.12.3
  • better-sqlite3: 8.4.0

2. 安装

sh
# 安装 node-gyp
npm i node-gyp -g

# 安装 构建工具
npm install --save-dev @electron/rebuild

# (必须)重新构建适合当前操作系统的sqlite
npm i better-sqlite3@8.4.0
# re-sqlite的脚本内容为: electron-rebuild -f -w better-sqlite3
npm run re-sqlite

# 如果sqlite报错 ...tools之类的
npm --vs2015 i -g --production windows-build-tools
# 或
npm i -g --production windows-build-tools

# 或 删除整个node_modules,重新安装
# 或 重新安装 Visual Studio Community

出现的问题

1. ModuleNotFoundError: No module named 'distutils'

详细错误如下:

sh
 Building module: better-sqlite3, Completed: 0Attempting to build a module with a space in the path
See https://github.com/nodejs/node-gyp/issues/65#issuecomment-368820565 for reasons why this may not work
 Building module: better-sqlite3, Completed: 0Traceback (most recent call last):
  File "C:\0-E\Code Store\hz-for-book\node_modules\node-gyp\gyp\gyp_main.py", line 42, in <module>
    import gyp  # noqa: E402
    ^^^^^^^^^^
  File "C:\0-E\Code Store\hz-for-book\node_modules\node-gyp\gyp\pylib\gyp\__init__.py", line 9, in <module>
    import gyp.input
  File "C:\0-E\Code Store\hz-for-book\node_modules\node-gyp\gyp\pylib\gyp\input.py", line 19, in <module>
    from distutils.version import StrictVersion
ModuleNotFoundError: No module named 'distutils'
Error: `gyp` failed with exit code: 1
    at ChildProcess.onCpExit (C:\0-E\Code Store\hz-for-book\node_modules\node-gyp\lib\configure.js:325:16)
    at ChildProcess.emit (node:events:517:28)
    at ChildProcess._handle.onexit (node:internal/child_process:292:12)

 Rebuild Failed

An unhandled error occurred inside electron-rebuild
node-gyp failed to rebuild 'C:\0-E\Code Store\hz-for-book\node_modules\better-sqlite3'

Error: node-gyp failed to rebuild 'C:\0-E\Code Store\hz-for-book\node_modules\better-sqlite3'
    at ChildProcess.<anonymous> (C:\0-E\Code Store\hz-for-book\node_modules\@electron\rebuild\lib\module-type\node-gyp\node-gyp.js:118:24)
    at ChildProcess.emit (node:events:517:28)
    at ChildProcess._handle.onexit (node:internal/child_process:292:12)

这个问题的解决方法是我在better-sqlite3官方仓库中issues#1154找到的。在控制台执行以下命令安装一下对应的库就行:

sh
pip install setuptools