javascript开发桌面应用环境搭建之electron结合react
安装react
npx create-react-app gui-app
安装electron
//安装electron
1. npm config set ELECTRON_MIRROR http://npm.taobao.org/mirrors/electron/
2. npm install --save-dev electron
创建electron入口
项目根目录新建main.js
const { app, BrowserWindow} = require('electron')
const path = require('path')
const isDev = require('electron-is-dev')
function createWindow() {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
},
})
//判断是否是开发模式
const urlLocation = isDev ? 'http://localhost:3000' : `file://${path.join(__dirname, './build/index.html')}`
mainWindow.loadURL(urlLocation)
mainWindow.webContents.on("did-finish-load", () => {
})
mainWindow.webContents.on('dom-ready', () => {
})
mainWindow.once('ready-to-show', function () {
mainWindow.show();
})
}
app.on('ready', () => {
createWindow();
});
// Quit when all windows are closed.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
准备包
react更新同步更新electron
//安装concurrently
npm install concurrently --save-dev
//安装wait-on
npm install wait-on --save-dev
更新不打开浏览器
//安装
npm install cross-env
electron热更新
//安装nodemon
npm install -g nodemon
判断是否开发环境
//安装electron-is-dev
npm install electron-is-dev
package.json配置
{
"name": "gui-app",
"version": "0.1.0",
"description": "Hello World!",
++ "main": "main.js",
"author": "Jane Doe",
"license": "MIT",
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
++ "gui": "nodemon --ignore ./package.json --exec concurrently \"wait-on http://localhost:3000 && electron .\" \"cross-env BROWSER=none yarn start\""
}
...
}
运行
npm run gui
打包
快捷的打包方式
yarn add --dev @electron-forge/cli
npx electron-forge import
yarn run make
打包后运行
运行如下文件
D:\你的目录\gui-app\out\gui-app-win32-x64\gui-app.exe