用Electron开发桌面应用,比你想象的还简单。下面手把手来搭建一个基于React和Electron的桌面应用架子或者称之为DEMO, 完整代码
开发环境
基本环境node和npm
步骤 1. 安装Electron
npm i -D electron@latest
步骤 2. 克隆示例项目的仓库,快速启动自己的第一个桌面应用
# 克隆示例项目的仓库
$ git clone https://github.com/electron/electron-quick-start
# 进入这个仓库
$ cd electron-quick-start
# 安装依赖并运行
$ npm install && npm start
到这一步,已经成功跑起一个Electron项目了
步骤 3. 安装webpack用来打包前端文件
npm i --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin
在开发模式下,我们需要使用webpack-dev-server,使用html-webpack-plugin进行build文件自动注入index.html中
步骤 4. 配置webpack,在根目录下创建webpack.config.js
const webpack = require('webpack');
const htmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
entry: [
'./app/index.jsx'
],
output: {
path: path.resolve(__dirname, 'uiDist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
loaders: ['babel-loader'],
exclude: /(node_modules)/
}
]
},
plugins: [
new htmlWebpackPlugin({
title: 'Electron DEMO',
template: './index.html'
})
]
}
上面使用了babel将es6转换为es5支持,所以下面我们要按照babel和react相关的依赖,我们把所有前端文件放在app文件下(自己创建的一个文件夹),把最终打包的代码放在uiDist文件夹中
步骤 5. 安装react 和 react-dom 和babel依赖
npm i --save react-dom react
npm i --save-dev @babel/core @babel/preset-env @babel/preset-react babel-loader
这里还需要在webpack.config.js所在文件夹下,创建.babelrc
{
"presets": ["@babel/env", "@babel/react"]
}
在app文件下添加index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
render() {
return (
Hello world
)
}
}
ReactDOM.render( , document.getElementById('root'));
修改根目录下的index.html
<%= htmlWebpackPlugin.options.title %>
现在执行webpack -p --config ./webpack.config.js
就可以对前端文件进行打包,运行webpack-dev-server --devtool eval --progress --colors --content-base build
就可以启动一个可以访问的server。下面我们把运行webpack的命令写入package.json的scripts来调用:
"scripts": {
"start": "electron .",
"build": "webpack -p --config ./webpack.config.js",
"devWeb": "webpack-dev-server --devtool eval --progress --colors --content-base build"
},
现在我们就可以直接运行npm run devWeb
来跑起一个web server用来开发调试,运行npm run build
来打包前端文件。
在这一步,我们发现运行npm run start
打开electron, 并没有得到我们预想的结果。那是因为我们需要对electron的main.js 的mainWindow.loadFile
加载的文件做一个修改。
步骤 6. 修改根目录下的main.js文件下的mainWindow.loadFile路径
// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')
// 根据NODE_ENV来判断是否为开发模式
const isDev = process.env.NODE_ENV === 'dev';
// 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,
webPreferences: {
javascript: true,
plugins: true,
nodeIntegration: false,
webSecurity: false,
preload: path.join(__dirname, 'renderer.js') // 自动注入render.js Electron的API使用文件
}
})
// and load the index.html of the app.
if (isDev) {
// 开发模式访问开发地址
mainWindow.loadURL('http://localhost:8080')
} else {
// 生产模式访问打包后的文件
mainWindow.loadFile('./uiDist/index.html')
}
// Open the DevTools.
// 开发模式才开启调试工具
isDev && 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 macOS 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 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 (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.
现在我们再给package.json的sciprts中,添加一个启动开发模式的electron命令:
"devElectron": "NODE_ENV=dev electron .",
现在开发模式我们只要npm run devElectron
和npm run devWeb
进行愉快的开发了。
最后一步,打包成桌面运用
这里以打包mac的app为例子
electron打包我们使用electron-builder, 首先安装
npm i --save-dev electron-builder
然后再package.json添加build字段配置, 同时再scripts中添加打包命令
"scripts": {
"start": "electron .",
"devElectron": "NODE_ENV=dev electron .",
"build": "webpack -p --config ./webpack.config.js",
"devWeb": "webpack-dev-server --devtool eval --progress --colors --content-base build",
"build_app": "electron-builder --mac --x64"
},
"build": {
"productName": "我的桌面应用",
"appId": "com.xxx.app",
"mac": {
"target": [
"dmg",
"zip"
]
}
}
现在我们执行npm run build_app
命令,就生成了我们的第一个桌面应用。