目录
2.3 更改package.json,为electron添加入口
4.2 使用electron-packager打包electron应用
说明
- 网上看了很多electron和react结合的示例,很多仍然没有做到很好的通信,有些一知半解,这里给出我自己的完整方案
- 其中react只是一个生成单页面的工具,理论上可以结合任何前端js库使用,当然也可以替换成Vue,Angular等MV*框架
- 这里以 Windows 10 系统为开发环境
1 安装React
这里使用create-react-app工具安装,前提是本地已经安装node环境
1.1 安装create-react-app
npm install create-react-app -g
1.2 创建react应用
create-react-app myapp
2 安装electron
2.1 在同级目录下安装electron
npm install electron --save-dev
2.2 添加electron启动文件main.js
在package.json同级目录下新建main.js,这里使用electron官网的配置,loadFile的目录需要修改
main.js内容如下,关于配置项官网有详细介绍,查看官网示例
// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')
// 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 = null;
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 900,
height: 600,
// transparent: true, // 透明窗口
opacity: 1, // 全局透明度
frame: true, // 隐藏所有操作栏
webPreferences: {
// 起用预加载文件,此文件可以使用node以及访问其余目录
// preload: path.join(__dirname, 'public/render.js')
}
})
// and load the index.html of the app.
// 打包时使用
// mainWindow.loadFile('./build/index.html')
// 本地调试时使用
mainWindow.loadURL('http://localhost:3000/')
// 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 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 m