官方例子
github链接
main.js
const { app, BrowserWindow } = require('electron')
说句实话这里的语法是有部分看不懂的。导入模块虽然electron
有很多模块。但是这里只是用到了app
和 BrowserWindow
function createWindow () {// Create the browser window.const mainWindow = new BrowserWindow({width: 800,height: 600,webPreferences: {preload: path.join(__dirname, 'preload.js')}})// and load the index.html of the app.mainWindow.loadFile('index.html')// Open the DevTools.// mainWindow.webContents.openDevTools()
}
创建窗口函数,new了一个BrowserWindow
。并指定了一些属性,然后加载html
文件
app.whenReady().then(() => {createWindow()app.on('activate', function () {// On macOS it's common to re-create a window in the app when the// dock icon is clicked and there are no other windows open.if (BrowserWindow.getAllWindows().length === 0) createWindow()})
})
当 app
whenReady
之后就可以创建窗口了,调用createWindow()
函数。
app.on('window-all-closed', function () {if (process.platform !== 'darwin') app.quit()
})
当所有窗口退出后。app
退出。
package.json
{"name": "electron-quick-start","version": "1.0.0","description": "A minimal Electron application","main": "main.js","scripts": {"start": "electron ."},"repository": "https://github.com/electron/electron-quick-start","keywords": ["Electron","quick","start","tutorial","demo"],"author": "GitHub","license": "CC0-1.0","devDependencies": {"electron": "^29.0.0"}
}
这个文件可以由npm init
自动生成。自动生成的文件需要将修改为
"scripts": {"start": "electron ."}
然后就可以通过 vscode直接运行electron程序了。