美文网首页
React创建Electron桌面应用

React创建Electron桌面应用

作者: 猪猪9527 | 来源:发表于2017-11-14 18:52 被阅读162次

创建一个简单的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就行了

相关文章

网友评论

      本文标题:React创建Electron桌面应用

      本文链接:https://www.haomeiwen.com/subject/siwfvxtx.html