electron-rebuild与react-scripts test冲突问题解决方案咨询
解决Node版本不匹配导致的native模块编译冲突问题
问题背景
react-scripts test 运行在标准Node环境,而应用运行在Electron编译的Node版本上,出现版本不匹配错误:
The module '.../better_sqlite3.node' was compiled against a different Node.js version using NODE_MODULE_VERSION 103. This version of Node.js requires NODE_MODULE_VERSION 93. Please try re-compiling or re-installing the module (for instance, using `npm rebuild` or `npm install`).
当前困境:执行npm rebuild后测试正常但应用启动失败;执行electron-rebuild后应用正常但测试失效,手动切换命令过于繁琐。
可行解决方案
方案1:用npm预脚本自动切换编译目标
直接在package.json的scripts中添加预执行脚本,让测试和Electron启动前自动完成对应环境的编译:
"scripts": { "pretest": "npm rebuild", "test": "react-scripts test", "prestart:electron": "electron-rebuild", "start:electron": "electron ." }
之后执行npm test会自动先运行npm rebuild适配标准Node环境;执行npm run start:electron会自动先运行electron-rebuild适配Electron环境,无需手动切换命令。
方案2:针对性编译单个native模块
如果只想编译better_sqlite3而非所有模块,能大幅提升编译速度,可在package.json中添加两个脚本:
"scripts": { "build:test": "npm rebuild better_sqlite3 --target=$(node -v) --dist-url=https://nodejs.org/download/release/", "build:electron": "electron-rebuild -f -w better_sqlite3" }
需要切换环境时,直接执行npm run build:test或npm run build:electron即可。
方案3:Mock测试环境的native依赖
如果测试不需要实际操作SQLite数据库,可直接在测试环境mock掉better_sqlite3,彻底规避版本冲突。在src/setupTests.js中添加:
jest.mock('better_sqlite3', () => { // 模拟业务所需的数据库方法,比如查询、插入等 return jest.fn(() => ({ prepare: jest.fn(() => ({ all: jest.fn(() => []), run: jest.fn() })) })); });
这样测试时完全无需编译native模块,也不会出现版本不匹配问题。
内容的提问来源于stack exchange,提问作者Molten Ice
相关产品推荐
相关产品推荐

