参考资料
https://www.electronjs.org/zh/docs/latest/tutorial/quick-start
https://www.electronjs.org/zh/docs/latest/tutorial/tutorial-first-app
创建
初始化项目
npm init
安装 Electron
npm install --save-dev electron
代码
请参考以下内容修改或创建对应文件。
package.json
{
"name": "my-app",
"version": "1.0.0",
"description": "Hello World!",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"author": "Anonymous",
"license": "MIT"
}
main.js
const { app, BrowserWindow } = require('electron')
const path = require('path')
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
preload.js
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector)
if (element) element.innerText = text
}
for (const type of ['chrome', 'node', 'electron']) {
replaceText(`${type}-version`, process.versions[type])
}
})
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
<p>
We are using Node.js <span id="node-version"></span>,
Chromium <span id="chrome-version"></span>,
and Electron <span id="electron-version"></span>.
</p>
</body>
</html>
运行
使用 npm start
启动程序
打包
Electron Forge 是一个用于打包和分发 Electron 应用程序的一体化工具。Electron Forge 是一个用于打包和分发 Electron 应用程序的一体化工具。
导入项目
npm install --save-dev @electron-forge/cli
npx electron-forge import
打包应用
Package
npm run package
Make
npm run make
Publish
npm run publish