快速初始化一个electron+react桌面应用项目

电玩女神 2023-03-01 14:56 87阅读 0赞

Step1: 初始化一个react应用

参考 react官方文档
这里要先要安装好create-react-app脚手架
安装指令如下:

  1. npm install -g create-react-app

安装好create-react-app脚手架之后,初始化一个react项目
指令如下:

  1. npx create-react-app react-electron-app

初始化完成之后执行:

  1. cd react-electron-app
  2. yarn start

之后会在浏览器中打开页面http://localhost:3000/
在这里插入图片描述

说明react项目已经初始化完成

Step2: 安装electron

安装electron

指令如下:

  1. npm install --save-dev electron

但是这一步,因为网络问题,很容易失败。
可以翻墙 多次尝试安装,也可以用cnpm安装
方法如下:

  1. #使用淘宝镜像
  2. npm install -g cnpm --registry=https://registry.npm.taobao.org
  3. #用cnpm安装electron
  4. cnpm install electron -g

Electron application 本质上是一个 Node. js 应用程序。
与 Node.js 模块相同,应用的入口是 package.json 文件。
一个最基本的 Electron 应用一般来说会有如下的目录结构:

  1. your-app/
  2. ├── package.json
  3. ├── main.js
  4. └── index.html

所以要在刚刚创建好的react项目进行如下修改

修改package.json

增加如下三处:main.js是electron项目必须的文件
在这里插入图片描述

在根目录下新增一个main.js文件,内容如下

关键是主window要加载url mainWindow.loadURL("http://localhost:3000/")

  1. // Modules to control application life and create native browser window
  2. const { app, BrowserWindow} = require('electron')
  3. const path = require('path')
  4. function createWindow () {
  5. // Create the browser window.
  6. const mainWindow = new BrowserWindow({
  7. width:600,
  8. height:300,
  9. webPreferences: {
  10. preload: path.join(__dirname, 'preload.js')
  11. }
  12. })
  13. // and load the index.html of the app.
  14. // mainWindow.loadFile('index.html')
  15. mainWindow.loadURL("http://localhost:3000/")
  16. // Open the DevTools.
  17. // mainWindow.webContents.openDevTools()
  18. }
  19. // This method will be called when Electron has finished
  20. // initialization and is ready to create browser windows.
  21. // Some APIs can only be used after this event occurs.
  22. app.whenReady().then(() => {
  23. createWindow()
  24. app.on('activate', function () {
  25. // On macOS it's common to re-create a window in the app when the
  26. // dock icon is clicked and there are no other windows open.
  27. if (BrowserWindow.getAllWindows().length === 0) createWindow()
  28. })
  29. })
  30. // Quit when all windows are closed, except on macOS. There, it's common
  31. // for applications and their menu bar to stay active until the user quits
  32. // explicitly with Cmd + Q.
  33. app.on('window-all-closed', function () {
  34. if (process.platform !== 'darwin') app.quit()
  35. })
  36. // In this file you can include the rest of your app's specific main process
  37. // code. You can also put them in separate files and require them here.

接下来就是最后一步,运行electron app

  1. npm run electron-start

会跑起来如下界面
在这里插入图片描述
至此,一个react+electron项目初始化完成,
要对页面进行修改,直接修改App.js文件即可

发表评论

表情:
评论列表 (有 0 条评论,87人围观)

还没有评论,来说两句吧...

相关阅读

    相关 快速初始化一个mpvue 项目

    > 小编推荐:[Fundebug][]提供JS错误监控、微信小程序错误监控、微信小游戏错误监控,Node.j错误监控和Java错误监控。真的是一个很好用的错误监控费服务,众多大