Create Project
- Create a project folder “demo” and open with VisualStudio Code
-
Open a new Terminal and initial project
1
npm init -y
-
Install electron package
1
npm install electron-prebuilt
-
Open package.json file and modify
1 2 3 4
"main": "src/main.js", "scripts": { "start": "electron ." },
-
Create src folder and main.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
const electron = require("electron") const path = require("path") const url = require("url"); const {app, BrowserWindow} = electron; let win app.on('ready', _ => { win = new BrowserWindow({ width: 800, height: 700, resizable: false }) win.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file', slashes: true })) win.setMenu(null) // win.webContents.openDevTools() win.on('closed', () => { win = null }) })
-
Create index.html under project folder
1 2 3 4 5 6 7 8
<html> <head> <title>Electron demo app</title> </head> <body> <h1>Hello World</h1> </body> </html>
-
In VSCode terminal ,run following command to start applicataion:
1
npm run start
Import Js
-
Create a new countdown.js file
1 2 3
module.exports = function countdown(tick){ console.log("in countdown.js " + tick) }
-
In main.js
1 2
const countdown = require('./countdown') countdown(3)
加回调函数:
-
Create a new countdown.js file
1 2 3 4
module.exports = function countdown(tick){ let count=3 tick(count) }
-
In main.js
1 2 3 4 5
const countdown = require('./countdown') countdown(count => { console.log("in main.js " + count) })
process间通信
-
修改 index.html 添加一个按钮
1 2 3 4 5 6 7 8 9
<body> <h1>Hello World</h1> <div class="container"> <div class="msg" id="msg"></div> <button class="btn" id="start">Start</button> </div> <script>require('./render')</script> </body>
-
创建render.js
1 2 3 4 5
const electron = require('electron') const ipc =electron.ipcRenderer document.getElementById('start').addEventListener('click',_ =>{ ipc.send('start') })
-
在main.js中监听此消息
1 2 3 4 5
const {app, BrowserWindow, ipcMain: ipc } = electron ipc.on('start', _ =>{ console.log("Get message from render") })
添加响应消息:
-
修改 main.js
1 2 3 4
ipc.on('start', _ =>{ console.log("get message from render") win.webContents.send('Response', "message from main") })
-
修改render.js
1 2 3
ipc.on('Response', (evt,msg)=>{ document.getElementById('msg').innerHTML=msg })
Build
-
Install following package:
1
npm install electron-packager rimraf -D
-
Add a new build script in package.json
1 2 3
"scripts": { "build": "rimraf demo-* && electron-packager . --platform=win32,linux --arch=x64", },
-
Run following command to build:
1
npm run build