npm init
npm install electron --save-dev
结果第一步就卡住了——装不上。
初步猜测是网络问题。虽然开梯子能解决,但不想一直挂着。查阅文档后发现,Electron 在国内需要配置镜像。
于是动手配置:
- 找到
.npmrc 文件,路径可通过 npm config list 查看 user 字段;
- 加入镜像地址:
electron_mirror=https://npmmirror.com/mirrors/electron/
小结
国内开发环境配置镜像算是常规操作,只是初次接触时容易让人心烦。
第二难:引入 Vue 与 Vite
官方示例虽然能运行,但没有热更新,开发效率低。既然选择了 Electron,自然要利用前端生态,于是决定引入 Vue 和 Vite,配合 vite-plugin-electron 替换原有结构。
思维方式需要转变:原本是加载本地 HTML 文件,现在则要加载 Vite 启动的本地服务:win.loadURL('http://localhost:3000')。
另一个问题是开发环境与生产环境的差异,需要引入环境变量。最终使用 cross-env 实现:
"dev": "cross-env NODE_ENV=development vite dev",
win.webContents.openDevTools({ mode: 'detach' })
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Electron with Vite",
"type": "node",
"request": "launch",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "dev"],
"windows": {
"runtimeExecutable": "npm.cmd"
},
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
"skipFiles": ["<node_internals>/**"],
"env": {
"NODE_ENV": "development",
"ELECTRON_IS_DEV": "true"
}
},
{
"name": "Attach to Renderer",
"type": "chrome",
"request": "attach",
"port": 9223,
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}/src/renderer",
"sourceMaps": true,
"sourceMapPathOverrides": {
"/@fs/*": "${webRoot}/*",
"/@id/*": "${webRoot}/*",
"/src/*": "${webRoot}/*",
"/node_modules/.vite/*": "${webRoot}/node_modules/*"
}
}
],
"compounds": [
{
"name": "Debug Main + Renderer",
"configurations": ["Debug Electron with Vite", "Attach to Renderer"]
}
]
}
electron_builder_binaries_mirror=https://npmmirror.com/mirrors/electron-builder-binaries/
outDir: fileURLToPath(new URL('./renderer-dist', import.meta.url))