完成了Electron的安装,第一件事必然要写一个HelloWorld试试效果了。
由于本人也是第一次接触,没有什么规范化的学习经验,基本上都是从网上的资料照搬自己尝试,也可能存在问题,尽力尽力。
要写HelloWorld,首先还是了解一下Electron的项目结构,首先是项目包(即一个文件夹),其中包含“app”文件夹和“main.js”、"package.json"两个文件,"app"文件夹中包含"index.html"文件。
- 首先将项目结构建立起来,接下来就可以复制代码了,因为是初学,本人暂时不考虑代码的意义,照搬就好。
main.js代码
const electron = require('electron'); // Module to control application life. const {app} = electron; // Module to create native browser window. const {BrowserWindow} = electron; // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let win; function createWindow() { // Create the browser window. win = new BrowserWindow({width: 1024, height: 768}); // and load the index.html of the app. win.loadURL(`file://${__dirname}/app/index.html`); // Open the DevTools. win.webContents.openDevTools(); // Emitted when the window is closed. win.on('closed', () => { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. win = null; }); } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.on('ready', createWindow); // Quit when all windows are closed. app.on('window-all-closed', () => { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { // On OS X 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 (win === null) { createWindow(); } }); // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and require them here.
Package.json代码
{ "name": "helloworld", "version": "0.1.0", "main": "./main.js", "scripts": { "start": "electron ." }, "devDependencies": { "electron-prebuilt": "^1.4.13" } }
index.html代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello,World</title> </head> <body> <h1>Hello,World!</h1> This is a HelloWorld program by Electron! </body> </html>
- 粘贴好代码后,即可使用Electron运行程序了。
有两种方式运行
(1)打开electron.exe主程序,将"HelloWorld"项目文件夹拖入"Drag your app here to run it"框框中,即可运行;
(2)打开cmd命令行,使用electron 你的HelloWorld项目文件夹路径,如"electron E:\HelloWorld"。