如何搭建Electron开发环境
原文發(fā)表于 https://lleohao.github.io/2017/09/02/如何搭建Electron開(kāi)發(fā)環(huán)境/
這個(gè)項(xiàng)目結(jié)構(gòu)是我在編寫(xiě) 基于Electron 和 Angular 的七牛文件上傳App 總結(jié)出來(lái)的
本文主要介紹如何從零開(kāi)始搭建高效的Electron開(kāi)發(fā)環(huán)境, 主要內(nèi)容如下:
通過(guò)合理的目錄劃分來(lái)組織代碼
使用npm script簡(jiǎn)化開(kāi)發(fā)
如何在渲染進(jìn)程開(kāi)發(fā)時(shí)使用熱更新
如何在主進(jìn)程開(kāi)發(fā)時(shí)使用自動(dòng)重啟
如何在主進(jìn)程開(kāi)發(fā)時(shí)使用Typescript
如何打包和發(fā)布軟件
示例項(xiàng)目地址 https://github.com/lleohao/el...
發(fā)現(xiàn) http://hao.jser.com/ 這個(gè)網(wǎng)站臭不要臉的轉(zhuǎn)載文章
目錄結(jié)構(gòu)劃分
初始化目錄
首先按照常規(guī)的方法新建一個(gè)項(xiàng)目文件夾(這里我的示例文件夾叫做electron-base, 然后使用npm init初始化目錄。
目前我們的開(kāi)發(fā)目錄如下:
electorn-base ├── .gitignore - git忽略文件 ├── LICENSE - 開(kāi)源協(xié)議 ├── README.md - 文檔 └── package.json - npm package目錄劃分
Electron 的開(kāi)發(fā)主要分為兩個(gè)部分, 其中主進(jìn)程(Main Process)主要負(fù)責(zé)打開(kāi)頁(yè)面和調(diào)用系統(tǒng)底層的資源等, 渲染進(jìn)程(Renderer Process)則是一個(gè)普通的網(wǎng)頁(yè)窗口.
兩個(gè)進(jìn)程的開(kāi)發(fā)有著不同的開(kāi)發(fā)方式, 主進(jìn)程更像是傳統(tǒng)Node的開(kāi)發(fā), 而渲染進(jìn)程則是普通的前端開(kāi)發(fā). 同時(shí)它們之間又有著可以共用的部分(如輔助函數(shù)、數(shù)據(jù)模型等), 因此可以按照下面的方式劃分
electorn-base ├── ... - 省略 └── src - 代碼源文件├── main - 主線程代碼├── renderer - 渲染線程└── shared - 公用代碼Electron quick start
接下來(lái)運(yùn)行npm install electron -D安裝Electron,同時(shí)在package.json添加main字段, 這代表整個(gè)項(xiàng)目的入口文件,這里我們先設(shè)置為src/main/main.js.
順便添加上兩個(gè)文件
# src/main.js const { app, BrowserWindow } = require('electron') const path = require('path') const url = require('url')let winfunction createWindow() {win = new BrowserWindow({ width: 800, height: 600 })win.loadURL(url.format({pathname: path.join(__dirname, '../renderer/index.html'),protocol: 'file:',slashes: true}))// 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 macOS it is common for applications and their menu bar// to stay active until the user quits explicitly with Cmd + Qif (process.platform !== 'darwin') {app.quit()} })app.on('activate', () => {// 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 (win === null) {createWindow()} }) <!-- src/renderer/index.html --> <!DOCTYPE html> <html><head><meta charset="UTF-8"><title>Hello World!</title></head><body><h1>Hello World!</h1>We are using node <script>document.write(process.versions.node)</script>,Chrome <script>document.write(process.versions.chrome)</script>,and Electron <script>document.write(process.versions.electron)</script>.</body> </html>在根目錄運(yùn)行electron .(或者是./node_modules/.bin/electron .)啟動(dòng)程序
為了以后方便啟動(dòng)程序, 將這段命令添加到package.json中
// package.json 部分內(nèi)容 "main": "src/main/main.js", "scripts": {"start": "./node_modules/.bin/electron ." }, "devDependencies": {"electron": "^1.7.5" }開(kāi)發(fā)渲染線程
渲染線程的開(kāi)發(fā)跟普通的前端開(kāi)發(fā)沒(méi)有多大的區(qū)別, 為了開(kāi)發(fā)的效率, 我們通常會(huì)選擇一款前端開(kāi)發(fā)框架, 這里我選擇的是Angular, 當(dāng)然也可以選擇其他的框架, 只需要按照下文中的要求修改打包路徑.
導(dǎo)入Angular(可選, 使用其他框架可以跳過(guò))
這里我使用Angular-cli工具來(lái)初始化項(xiàng)目
安裝cli工具
`npm install -g @angular/cli`初始化目錄
` ng new electron-base -sd src/renderer -si -sg -st --routing true --styles scss `修改.angular-cli.json
"apps": [{"root": "src/renderer", // 源文件目錄"outDir": "out/renderer", // 輸出目錄"baseHref": "./", // 解決打包后無(wú)法加載文件... }]如何在開(kāi)發(fā)過(guò)程中進(jìn)行代碼熱更新
前端開(kāi)發(fā)中, 我們可以使用webpack享受到自動(dòng)刷新、熱更新等方便的功能, 那么在Electron的開(kāi)發(fā)過(guò)程我們?nèi)绾蜗硎艿牡竭@些功能了?這里我們只需要簡(jiǎn)單的修改下main.js文件即可
function isDev() {return process.env['NODE_ENV'] === 'development' }function createWindow() {win = new BrowserWindow({ width: 800, height: 600 })if (isDev()) {// 這里的url換成你所使用框架開(kāi)發(fā)時(shí)的urlwin.loadURL('http://127.0.0.1:4200');} else {win.loadURL(url.format({pathname: path.join(__dirname, '../renderer/index.html'),protocol: 'file:',slashes: true}))}// 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}) }開(kāi)發(fā)時(shí)我們還是按照以前的方式啟動(dòng)一個(gè)webpcak服務(wù)器進(jìn)行開(kāi)發(fā), Electron通過(guò)HTTP協(xié)議打開(kāi)頁(yè)面, 這樣我們依舊可以享受到代碼熱更新等功能.
通過(guò)設(shè)置環(huán)境變量NODE_ENV來(lái)區(qū)分開(kāi)發(fā)和生成環(huán)境, 在package.json中添加兩個(gè)命令來(lái)方便開(kāi)發(fā)
"scripts": {"ng": "ng", // angular alias"start": "NODE_EBV=production ./node_modules/.bin/electron .", // 添加環(huán)境變量"dev:renderer": "ng serve" // 啟動(dòng)渲染線程開(kāi)發(fā)服務(wù)器 },打包渲染線程代碼
開(kāi)發(fā)完成后我們需要將前端的代碼進(jìn)行代碼打包, 一個(gè)好的習(xí)慣是將代碼的打包目錄放置在項(xiàng)目的根目錄中, 這里我將前端的打包目錄設(shè)置在out/renderer中
Angular項(xiàng)目只需要修改.angular-cli.json中的outDir字段, 其他的框架可以自行修改.
在package.json中添加打包命令
"scripts": {...."build:renderer": "ng buidl --prod" // 打包渲染線程代碼 },開(kāi)發(fā)主線程
主線程的開(kāi)發(fā)如Node程序的開(kāi)發(fā)沒(méi)有多大的區(qū)別, 這里就不多贅述.
雖然Node對(duì)ES6的支持已經(jīng)很完善了, 但更新的標(biāo)準(zhǔn)的支持就不怎么好, 這里我們可以使用Babel之類的工具進(jìn)行來(lái)使用最新的語(yǔ)法.
這里我推薦使用Typescript, 優(yōu)點(diǎn)主要有三個(gè):
靜態(tài)檢查, 畢竟是主線程的代碼, 有點(diǎn)錯(cuò)誤可就是程序直接崩潰的節(jié)奏
自動(dòng)提示, 這個(gè)不解釋
編譯方便, 比起B(yǎng)abel的配置文件, Typescript的配置要簡(jiǎn)單的多
使用Typescript (不使用的可以跳過(guò))
安裝Typescript
運(yùn)行npm install typescript -D
添加配置文件, 在src目錄下添加tsconfig.main.json文件
{"compilerOptions": {"outDir": "../out", // 輸出目錄, 同渲染線程放在一起"sourceMap": true, // 調(diào)試時(shí)需要"moduleResolution": "node","emitDecoratorMetadata": true,"experimentalDecorators": true,"target": "es6", // 輸出代碼版本, 由于在Node中運(yùn)行, es6沒(méi)問(wèn)題"module": "commonjs", // module 處理方式"typeRoots": [ // .d.ts 目錄"../node_modules/@types"],"lib": [ // 可選, 添加新的語(yǔ)法支持"es2017"]},"exclude": [ // 排除渲染線程目錄"renderer"] }在package.json中添加開(kāi)發(fā)和打包命令
"scripts": { ..."dev:main": "tsc -p ./src/tsconfig.main.json -w", // 開(kāi)發(fā)"build:main": "tsc -p ./src/tsconfig.main.json" // 打包 }主線程調(diào)試 (使用的編輯器是vscode)
添加啟動(dòng)配置文件, 項(xiàng)目根目錄新建.vscode文件夾,在其中新建launch.json
{// Use IntelliSense to learn about possible Node.js debug attributes.// Hover to view descriptions of existing attributes.// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387"version": "0.2.0","configurations": [{"type": "node","request": "launch","name": "Launch Program","cwd": "${workspaceRoot}","runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron","program": "${workspaceRoot}/src/main/main.ts", // 你的主文件"sourceMaps": true, "outFiles": ["${workspaceRoot}/out/**/*.js" // 你的輸出文件目錄](méi),"env": {"NODE_ENV": "development"}}] }使用組合鍵ctrl + f5啟動(dòng)程序
在文件中添加斷點(diǎn)進(jìn)行調(diào)試
主線程開(kāi)啟自動(dòng)刷新 (可選)
我們的渲染線程可以做到代碼變更后自動(dòng)刷新頁(yè)面, 在主線程的開(kāi)發(fā)中我們可以使用 nodemon 來(lái)實(shí)現(xiàn)同樣的功能
安裝nodemon
npm install nodemon -D
修改啟動(dòng)命令
"scripts": {"start": "nodemon --watch src/main --watch src/shared --exec './node_modules/.bin/electron' ./out/main/main.js" }以后開(kāi)發(fā)時(shí)只需要運(yùn)行npm start就可做到主線程的自動(dòng)刷新
打包主線程
主線程的開(kāi)發(fā)過(guò)程我們可能會(huì)使用其他的構(gòu)建工具, 這里我們同渲染線程一樣, 將主線程的打包文件放在out目錄中, 至此打包目錄的結(jié)構(gòu)應(yīng)當(dāng)如下
out ├── main - 主線程打包文件位置 │ └── main.js - 入口文件 ├── renderer - 渲染線程打包位置 │ ├── .... │ └── index.html - 入口頁(yè)面 └── shared - 公用文件└── utils.js打包和發(fā)布
electron-builder 可以將我們的程序打包成可執(zhí)行文件, 它的配置信息發(fā)在package.json中
這里配置的是Mac的打包信息, 具體的可以自行查閱文檔
{"main": "out/main/main.js", // 入口文件"scripts": {..."pack": "electron-builder -m --dir", // 簡(jiǎn)單打包軟件, 用于測(cè)試"dist": "electron-builder -m", // 正式打包軟件"build": "npm run build:renderer && npm run build:main && npm run dist" // 打包軟件},"build": {"appId": "com.lleohao.sample", // 自行修改 "mac": {"category": "public.app-category.productivity" // 自行修改}} }運(yùn)行npm build即可打包軟件
開(kāi)發(fā)流程
運(yùn)行npm run dev:renderer啟動(dòng)渲染線程開(kāi)發(fā)
運(yùn)行npm run dev:main啟動(dòng)主線程開(kāi)發(fā)
運(yùn)行npm start打開(kāi)Electron程序
運(yùn)行npm build打包程序
示例項(xiàng)目地址 https://github.com/lleohao/el...
總結(jié)
以上是生活随笔為你收集整理的如何搭建Electron开发环境的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Android -- 处理ViewPag
- 下一篇: !JS实战之随机像素图