序言
今天给项目升级Electron版本,本以为是改下版本号,重新下载依赖版本就能解决的事情。由于没有看官网文档的版本重大更改的记录,折腾了不少时间。记录下升级避坑步骤。
选择升级Electron版本
看官网的版本发布,目前最新版是Electron 16,为了稳妥起见,所以选择升级Electron 15
选择升级Node版本
官网要求:Node v16.5.0.
使用 nvm 管理 Node 版本
nvm install 16.5.0
更改package.json文件中的依赖版本
只需要把 "electron": "^11.0.0" 改成 "electron": "^15.0.0",附上完整文件:
{
"author": "HZ",
"name": "HZ",
"version": "1.0.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"electron:build": "vue-cli-service electron:build",
"electron:serve": "vue-cli-service electron:serve",
"postinstall": "electron-builder install-app-deps",
"postuninstall": "electron-builder install-app-deps"
},
"main": "background.js",
"dependencies": {
"axios": "^0.21.1",
"core-js": "^3.6.5",
"element-plus": "1.0.2-beta.71",
"localforage": "^1.9.0",
"vue": "^3.0.0",
"vue-i18n": "^9.1.6",
"vue-router": "^4.0.0-0",
"vuex": "^4.0.0-0"
},
"devDependencies": {
"@types/electron-devtools-installer": "^2.2.0",
"@typescript-eslint/eslint-plugin": "^4.18.0",
"@typescript-eslint/parser": "^4.18.0",
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-plugin-router": "~4.5.0",
"@vue/cli-plugin-typescript": "~4.5.0",
"@vue/cli-plugin-vuex": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"@vue/compiler-sfc": "^3.0.0",
"@vue/eslint-config-typescript": "^7.0.0",
"babel-plugin-component": "^1.1.1",
"electron": "^15.0.0",
"electron-devtools-installer": "^3.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^7.0.0",
"sass": "^1.26.5",
"sass-loader": "^8.0.2",
"typescript": "~4.1.5",
"vue-cli-plugin-electron-builder": "~2.1.1",
"vue-cli-plugin-element-plus": "~0.0.13"
}
}
删除旧的node_modules
推荐使用 rimraf
安装
npm install rimraf -g
删除
rimraf node_modules
重新下载依赖
yarn install
出现报错
下载完成后,重跑项目,发现报错 require is not defined,查找了许久,在官网的重大更改的计划重写的 API (12.0)有提示:
默认更改: contextIsolation 默认为 true
在 Electron 12, contextIsolation 将默认启用。 要恢复 上一个行为, contextIsolation: false 必须在 Web 首选项中指定。
我们 建议启用contextIsolation ,以保证您的应用程序的安全性。
Another implication is that require() cannot be used in the renderer process unless nodeIntegration is true and contextIsolation is false.(翻译:另一个含义是,除非nodeIntegration为true,contextIsolation为false,否则不能在呈现程序进程中使用require()。)
在 background.ts 中, webPreferences 修改下配置:
new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
})
重新运行项目、编译打包都正常了。