1,安裝nodejs,yarn
2,新建目錄,安裝electron
mkdir test?
cd test
npm init
npm install --save-dev electron
2,修改package.json
將
"scripts": {
? ? "test": "echo \"Error: no test specified\" && exit 1"
? },
修改為:
"scripts": {
? ? "start": "electron ."
? },
3,添加你要顯示的index.html文件
<!DOCTYPE html>
<html>
? <head>
? ? <meta charset="UTF-8">
? ? <title>hello</title>
? </head>
? <body>
? ? <div id="content">this is pc app</div>
? </body>
</html>
4,添加index.js
const { app, BrowserWindow } = require('electron')
// 保持對window對象的全局引用,如果不這么做的話,當(dāng)JavaScript對象被
// 垃圾回收的時候,window對象將會自動的關(guān)閉
let win
function createWindow () {
? // 創(chuàng)建瀏覽器窗口。
? win = new BrowserWindow({
? ? width: 840,
? ? height: 800,
? ? webPreferences: {
? ? ? nodeIntegration: true
? ? }
? })
? win.setMenu(null)
? // 加載index.html文件
? win.loadFile('index.html')
? // 打開開發(fā)者工具
? //win.webContents.openDevTools()
? // 當(dāng) window 被關(guān)閉,這個事件會被觸發(fā)。
? win.on('closed', () => {
? ? // 取消引用 window 對象,如果你的應(yīng)用支持多窗口的話,
? ? // 通常會把多個 window 對象存放在一個數(shù)組里面,
? ? // 與此同時,你應(yīng)該刪除相應(yīng)的元素。
? ? win = null
? })
}
// Electron 會在初始化后并準(zhǔn)備
// 創(chuàng)建瀏覽器窗口時,調(diào)用這個函數(shù)。
// 部分 API 在 ready 事件觸發(fā)后才能使用。
app.on('ready', createWindow)
// 當(dāng)全部窗口關(guān)閉時退出。
app.on('window-all-closed', () => {
? // 在 macOS 上,除非用戶用 Cmd + Q 確定地退出,
? // 否則絕大部分應(yīng)用及其菜單欄會保持激活。
? if (process.platform !== 'darwin') {
? ? app.quit()
? }
})
app.on('activate', () => {
? // 在macOS上,當(dāng)單擊dock圖標(biāo)并且沒有其他窗口打開時,
? // 通常在應(yīng)用程序中重新創(chuàng)建一個窗口。
? if (win === null) {
? ? createWindow()
? }
})
// 在這個文件中,你可以續(xù)寫應(yīng)用剩下主進(jìn)程代碼。
// 也可以拆分成幾個文件,然后用 require 導(dǎo)入。
5,運(yùn)行程序
npm start
6,安裝electron-build
yarn add electron-builder --dev
7,打包成exe安裝包
./node_modules/.bin/build
生成的安裝包在dist目錄下。
Tips:
如果要添加文件進(jìn)安裝包,可以在package.json添加配置:
"build":{
? ? "extraFiles": [
? ? ? "文件路徑"
? ? ]
? }
如果要用nodejs操作dom,需要在index.html引入該js, 如:
<script src="./renderer.js"></script>