React創建Electron桌面應用

創建一個簡單的Electron桌面應用

在GitHub上有個

electron-quick-start

的倉庫,需要本地計算機安裝好Git(比如SourceTree)和Node.js,使用步驟如下:

# 克隆倉庫

git clone https://github.com/electron/electron-quick-start

# 使用命令行進入倉庫所在文件夾

cd electron-quick-start

# 安裝依賴

npm install

# 運行應用

npm start

image

Electron詳細文檔可以參看官方文檔

創建一個React項目(內容引用《深入淺出React和Redux》,侵刪)

React技術依賴于一個很龐大的技術棧,比如,轉譯JavaScript代碼需要用到Babel,模塊打包工具又要用到Webpack,定制build過程需要grunt或者gulp……這些技術棧都需要各自的配置文件,還沒有開始寫一行React相關代碼,開發人員就已經被各種技術名詞淹沒。

針對這種情況,React的創建者Facebook提供了一個快速開發React應用的工具,名叫create-react-app,這個工具的目的是將開發人員從配置工作中解脫出來,無需過早關注這些技術棧細節,通過創建一個已經完成基本配置的應用,讓開發者快速開始React應用的開發,并且提供了熱調試環境。

create-react-app是一個通過npm發布的安裝包,在確認Node.js和npm安裝好之后,命令行中執行下面的命令安裝create-react-app:
npm install --global create-react-app

安裝過程結束之后,你的電腦中就會有create-react-app這樣一個可以執行的命令,這個命令會在當前目錄下創建指定參數名的應用目錄。
我們在命令行中執行下面的命令:
create-react-app test_app
這個命令會在當前目錄下創建一個名為test_app的目錄,在這個目錄中會自動添加一個應用的框架,隨后我們只需要在這個框架的基礎上修改文件就可以開發React應用,避免了大量的手工配置工作:
在create-react-app命令一大段文字輸出之后,根據提示,輸入下面的命令:
cd test_app
npm start
這個命令會啟動一個開發模式的服務器,同時也會讓你的瀏覽器自動打開了一個網頁,指向本機地址http://localhost:3000/ ,顯示界面如下圖所示。

image

整合Electron和React

Create React App創建的項目是一個純前端項目,整合React項目和Electron并且保留熱調試和本地包引用需要一下幾個簡單的操作:

1.需要安裝electron以及增加啟動命令

使用命令npm install -save electron安裝electron

在腳本里添加啟動命令"electron-start": "electron ."

image

2. 需要在React項目的根目錄(不是src目錄)創建Electron的啟動文件main.js(main.js文件可以直接拷貝electron-quick-start倉庫里的main.js)

const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow

const path = require('path')
const url = require('url')

// 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 mainWindow

function createWindow () {
    // Create the browser window.
    mainWindow = new BrowserWindow({width: 800, height: 600})

    // and load the index.html of the app.
    // mainWindow.loadURL(url.format({
    //     pathname: path.join(__dirname, 'index.html'),
    //     protocol: 'file:',
    //     slashes: true
    // }))
    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, './build/index.html'),
        protocol: 'file:',
        slashes: true }));

    // Open the DevTools.
    // mainWindow.webContents.openDevTools()

    // Emitted when the window is closed.
    mainWindow.on('closed', function () {
        // 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.
        mainWindow = 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', function () {
    // 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', function () {
    // 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 (mainWindow === 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.
image

3. 在React項目中的package.json文件中增加main字段,值為"main.js"

image

4.修改main.js中的win.loadURL,改為

mainWindow.loadURL(url.format({
pathname: path.join(__dirname, './build/index.html'), protocol: 'file:', slashes: true }))

image

到目前為止,在根目錄下運行npm run build + npm run electron-start 就可以啟動React創建的桌面應用了。

image

運行結果如下:

image

發現是一個內容為空的界面,我們還需要做如下修改:

在文件package.json中添加字段 "homepage":"."

原因:默認情況下,homepage是http://localhost:3000,build后,所有資源文件路徑都是/static,而Electron調用的入口是file:協議,/static就會定位到根目錄去,所以找不到靜態文件。在package.json文件中添加homepage字段并設置為"."后,靜態文件的路徑就變成了相對路徑,就能正確地找到了。

image

在根目錄下運行npm run build + npm run electron-start,運行結果如下:

image

這樣就結束了嗎?大家再仔細回顧下,我們修改完配置之后運行了兩條命令npm run build和npm run electron-start,每次都要npm run build后才能看到修改結果,而前面的內容提到過create-react-app提供了熱調試環境,我們怎么在Electron中使用熱調試呢?簡單來說就是代碼的修改能及時反饋到UI上,不需要做任何額外的操作呢?

簡單。在main.js文件中將啟動頁修改為

http://localhost:3000/

win.loadURL('http://localhost:3000/')

開發時,需要啟動兩個終端,一個終端啟動npm start, 另一個終端啟動npm run electron-start,這樣在electron中就可以熱調試了。

不過編譯發布時需要改回從build/index.html,這樣很麻煩,可以在package.json中定義個DEV字段,設置為true/false,然后修改main.js,代碼如下:

const pkg = require('./package.json') // 引用package.json 
//判斷是否是開發模式 
if(pkg.DEV) { 
  win.loadURL("http://localhost:3000/")
} else { 
  win.loadURL(url.format({
    pathname:path.join(__dirname, './build/index.html'), 
    protocol:'file:', 
    slashes:true 
  }))
}

以后運行npm run electron-start 之前,根據需要修改DEV為true/false就行了

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容