快速初始化一个electron+react桌面应用项目
Step1: 初始化一个react应用
参考 react官方文档
这里要先要安装好create-react-app脚手架
安装指令如下:
npm install -g create-react-app
安装好create-react-app脚手架之后,初始化一个react项目
指令如下:
npx create-react-app react-electron-app
初始化完成之后执行:
cd react-electron-app
yarn start
之后会在浏览器中打开页面http://localhost:3000/
说明react项目已经初始化完成
Step2: 安装electron
安装electron
指令如下:
npm install --save-dev electron
但是这一步,因为网络问题,很容易失败。
可以翻墙 多次尝试安装,也可以用cnpm安装
方法如下:
#使用淘宝镜像
npm install -g cnpm --registry=https://registry.npm.taobao.org
#用cnpm安装electron
cnpm install electron -g
Electron application 本质上是一个 Node. js 应用程序。
与 Node.js 模块相同,应用的入口是 package.json 文件。
一个最基本的 Electron 应用一般来说会有如下的目录结构:
your-app/
├── package.json
├── main.js
└── index.html
所以要在刚刚创建好的react项目进行如下修改
修改package.json
增加如下三处:main.js是electron项目必须的文件
在根目录下新增一个main.js文件,内容如下
关键是主window要加载url mainWindow.loadURL("http://localhost:3000/")
// Modules to control application life and create native browser window
const { app, BrowserWindow} = require('electron')
const path = require('path')
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width:600,
height:300,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
// and load the index.html of the app.
// mainWindow.loadFile('index.html')
mainWindow.loadURL("http://localhost:3000/")
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// 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.whenReady().then(() => {
createWindow()
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 (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
// 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.
接下来就是最后一步,运行electron app
npm run electron-start
会跑起来如下界面
至此,一个react+electron项目初始化完成,
要对页面进行修改,直接修改App.js文件即可
还没有评论,来说两句吧...