開發環境
1. Node.js
2.VsCode
建檔
- 創建一個資料夾
npm init -y
npm install electron
- 修改package.json裡的script。要測試畫面直接npm run start。
npm i electron-packager --save-dev
- 再來繼續在script中新增指令,npm run build拿來打包程式。
{"name": "Demo","version": "1.0.0","description": "","main": "main.js","scripts": {"start": "electron index.js","build": "electron-packager . JayApp --asar=true"},"keywords": [],"author": "","license": "ISC","dependencies": {"electron": "^4.0.0"},"devDependencies": {"electron-packager": "^13.0.1"}}
electron-packager . JayApp: 將目前全部資料打包成JayApp這個名字
— platform = darwin(Mac),win32(Windows),linux(LINUX)
— arch = ia32,x64,all
— version = Electron版本
— icon = icon路徑
— asar = true or false,設定true是把程式文件封裝,比較不容易被看到原始碼
— out = 輸出文件名稱(dist)
— ignore = 忽略檔案不要打包,建議把electron都忽略掉,因為打包後裡面就有了,可以減少檔案大小
— version-string.CompanyName = 新增安裝檔公司名稱
— version-string.ProductName = 新增安裝檔產品名稱
7.建立其他檔案,index.html、index.js
const electron = require('electron')const { app, BrowserWindow } = electron// 一開始載入新視窗app.on('ready', () => {let win = new BrowserWindow({width: 800,height: 600})win.loadURL(`file://${__dirname}/index.html`)})// 匯出用以開新視窗exports.openWindow = filename => {// win.currentOpenWindow().close()let win = new BrowserWindow({width: 800,height: 600})win.loadURL(`file://${__dirname}/` + filename + `.html`)}
跳頁
點擊button跳頁,程式寫在index.html裡的JS。跳頁後的畫面再另外寫個html及JS。
const remote = require('electron').remoteconst main = remote.require('./index.js')var button = document.querySelector('button')button.addEventListener('click', () => {main.openWindow('newPage')window.close() // 關閉自己})