如何使用 React 构建 Electron 应用。简介 先决条件 入门 打包应用 背景 后续

2025-06-04

如何使用 React 构建 Electron 应用程序。

介绍

先决条件

开始

打包应用程序

背景背景

跟进

介绍

我一直对编写桌面应用程序有着浓厚的兴趣。多年来,我一直对学习 C++ 或 Java 来编写这些程序不感兴趣。我想用 JavaScript 构建桌面应用程序,所以我选择了 Electron,一个由 Github 开发和维护的 JavaScript 桌面应用程序框架。

Electron 如此强大,它允许你用一份代码库为所有主流操作系统创建桌面应用。这给我留下了深刻的印象,但更让我印象深刻的是,你可以用 React、Angular、Vue 或任何 JavaScript 框架来编写桌面应用。他们就是靠这个说服我的。

在本教程中,我将概述帮助您入门的初始设置。

先决条件

要理解本教程的语法和概念,您应该具备:

  • Javascript 和 React 的基本概念
  • 按照 ES5 和 ES6 标准编写的 Javascript
  • 使用 Node 包管理器 (npm)
  • 安装 Nodejs 和 npm/yarn

开始

让我们创建一个文件夹来存放电子应用程序并将目录更改为该文件夹。

$ mkdir electron_react_app && cd $_
Enter fullscreen mode Exit fullscreen mode

使用 CRA(create-react-app)cli 为我们生成 React 代码库

$ npx create-react-app .
Enter fullscreen mode Exit fullscreen mode

由于我们使用电子,因此我们将在整个教程中添加相关的依赖项。

$ yarn add electron electron-builder wait-on concurrently -D
Enter fullscreen mode Exit fullscreen mode
  • electron- 允许我们使用电子框架。
  • electron-builder- 允许我们将电子应用程序构建为可执行文件。
  • wait-on- 让您在开发过程中等待反应编译,以便使用电子进行渲染。
  • concurrently- 允许我们同时运行 React 和 Electron。
$ yarn add electron-is-dev
Enter fullscreen mode Exit fullscreen mode
  • electron-is-dev- 告诉电子我们正在工作的当前环境,以决定是服务构建还是渲染在dev环境上运行的反应应用程序。

electron.js在公共文件夹中创建一个文件来存放我们的电子逻辑。

// public/electron.js
const electron = require("electron");
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;

const path = require("path");
const isDev = require("electron-is-dev");

let mainWindow;

function createWindow() {
  // Define the applications dimension
  mainWindow = new BrowserWindow({ width: 900, height: 680 });
  // Determine what to render based on environment
  mainWindow.loadURL(
    isDev
      ? "http://localhost:3000"
      : `file://${path.join(__dirname, "../build/index.html")}`
  );

  // Show chrome developer tools when in dev environment
  if (isDev) {
    mainWindow.webContents.openDevTools();
  }
  // Create event to close window on close
  mainWindow.on("closed", () => (mainWindow = null));
}

// On launch create app window
app.on("ready", createWindow);
app.on("window-all-closed", () => {
    // Based on which operating system you are using
  if (process.platform !== "linux") {
      // If os not linux, close the app
      // you can add darwin(mac os), win64 and so many more
    app.quit();
  }
});

app.on("activate", () => {
  if (mainWindow !== null) {
    createWindow();
  }
});
Enter fullscreen mode Exit fullscreen mode

接下来,我们将向package.json脚本标签添加一个命令,以同时运行 react 和 electron。

"electron-dev": "concurrently \"BROWSER=none yarn start\" \"wait-on http://localhost:3000 && electron .\""
Enter fullscreen mode Exit fullscreen mode

该脚本将等待 CRA 编译 react 应用程序然后启动 electron 应用程序。

另外,为了启动 Electron 应用,你需要指定 Electron 逻辑代码所在的位置。我们将在 中package.json添加main值来实现这一点。

"main": "public/electron.js"
Enter fullscreen mode Exit fullscreen mode

让我们运行我们的应用程序。

$ yarn electron-dev
Enter fullscreen mode Exit fullscreen mode

你应该看看这个。

2019-12-28 10-04-16截图.png

对于以前使用过 React 的人来说,你应该想知道为什么浏览器上的新标签没有打开,这是因为我们在运行时定义的环境electron-devBROWSER=none

现在,如果你像我一样需要访问 fs 模块,很快就会遇到“模块未找到”的错误。更多信息请点击此处

幸运的是,这个问题可以通过使用electron-renderer作为 Webpack 目标来解决。你不需要更改 React 代码中的任何其他内容,我们将使用一个名为Rescripts

让我们安装库

$ yarn add @rescripts/cli  @rescripts/rescript-env -D
Enter fullscreen mode Exit fullscreen mode

我们还必须更改package.json文件中的脚本标签


"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
Enter fullscreen mode Exit fullscreen mode


"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",
Enter fullscreen mode Exit fullscreen mode

接下来,将.rescriptsrc.js文件添加到根文件夹中,并添加以下行

module.exports = [require.resolve('./.webpack.config.js')]
Enter fullscreen mode Exit fullscreen mode

我们肯定需要创建该.webpack.config.js文件以避免导入错误。

module.exports = config => {
  config.target = 'electron-renderer';
  return config;
}
Enter fullscreen mode Exit fullscreen mode

现在你的fs担心已经结束了。

打包应用程序

为了打包我们的应用程序,我们需要一些依赖项。

yarn add electron-builder typescript -D
Enter fullscreen mode Exit fullscreen mode
  • electron-builder- 将应用程序及其所有依赖项打包在一起。
  • typescript-electron-builder依赖于 typescript >注意:您不会编写任何 typescript,我也不会强迫您使用它。

我们需要定义主页路由,因为 React 构建时使用绝对路径,而 Electron 不支持绝对路径。你可以在package.json文件内部通过添加homepage属性来更改它。

"homepage": "./",
Enter fullscreen mode Exit fullscreen mode

接下来,添加一个electron-pack命令,它将打包我们的构建。

将以下内容添加到您的scripts标签中package.json

"postinstall": "electron-builder",
"preelectron-pack": "yarn build",
"electron-pack": "build -mw"
Enter fullscreen mode Exit fullscreen mode
  • postinstall- 将确保您的依赖项始终与电子版本匹配
  • preelectron-pack- 将构建 React 应用程序
  • electron-pack- 为您选择的操作系统打包应用程序。

在运行任何操作之前,我们必须配置 Electron 构建器。

将以下内容添加到您的package.json文件中。

"author": {
  "name": "Your Name",
  "email": "your.email@domain.com",
  "url": "https://your-website.com"
},
"build": {
  "appId": "com.my-website.my-app",
  "productName": "MyApp",
  "copyright": "Copyright © 2019 ${author}",
  "mac": {
    "category": "public.app-category.utilities"
  },
  "files": [
    "build/**/*",
    "node_modules/**/*"
  ],
  "directories": {
    "buildResources": "assets"
  }
}
Enter fullscreen mode Exit fullscreen mode

您的package.json文件应该看起来像这样。

{
  "name": "my-app",
  "description": "Electron + Create React App + Electron Builder",
  "version": "0.1.0",
  "private": true,
  "author": {
    "name": "Your Name",
    "email": "your.email@domain.com",
    "url": "https://your-website.com"
  },
  "build": {
    "appId": "com.my-website.my-app",
    "productName": "MyApp",
    "copyright": "Copyright © 2019 ${author}",
    "mac": {
      "category": "public.app-category.utilities"
    },
    "files": [
      "build/**/*",
      "node_modules/**/*"
    ],
    "directories": {
      "buildResources": "assets"
    }
  },
  "dependencies": {
    "electron-is-dev": "^1.0.1",
    "react": "^16.8.3",
    "react-dom": "^16.8.3",
    "react-scripts": "2.1.5"
  },
  "homepage": "./",
  "main": "public/electron.js",
  "scripts": {
    "start": "rescripts start",
    "build": "rescripts build",
    "test": "rescripts test",
    "eject": "react-scripts eject",
    "electron-dev": "concurrently \"BROWSER=none yarn start\" \"wait-on http://localhost:3000 && electron .\"",
    "postinstall": "electron-builder",
    "preelectron-pack": "yarn build",
    "electron-pack": "build -mw"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "devDependencies": {
    "@rescripts/cli": "^0.0.10",
    "@rescripts/rescript-env": "^0.0.5",
    "concurrently": "^4.1.0",
    "electron": "^4.0.6",
    "electron-builder": "^20.38.5",
    "typescript": "^3.3.3333",
    "wait-on": "^3.2.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

您还需要创建一个名为 的目录,assets用于添加应用图标。点击此处查看这些图标的格式。

现在您可以打包您的应用程序

$ yarn electron-pack
Enter fullscreen mode Exit fullscreen mode

背景背景

如果你碰巧在linux上遇到这样的错误。

[2720:0425/142001.775056:FATAL:setuid_sandbox_host.cc(157)] The SUID sandbox helper binary was found, but is not configured correctly. Rather than run without sandboxing I'm aborting now. You need to make sure that /home/<name>/src/ssbc/patchwork/node_modules/electron/dist/chrome-sandbox is owned by root and has mode 4755.
Enter fullscreen mode Exit fullscreen mode

您可以通过添加此命令来修复该问题。

确保您位于项目目录中

$ sudo chown root node_modules/electron/dist/chrome-sandbox
Enter fullscreen mode Exit fullscreen mode

然后

$ sudo chmod 4755 node_modules/electron/dist/chrome-sandbox
Enter fullscreen mode Exit fullscreen mode

您的 Linux 软件包应用不会自动运行,因为它.Appimage默认带有扩展名。您必须将其设置为可执行文件。

确保您位于 dist 文件夹中

您可以通过以下方式进行操作:

$ chmod a+x '<You app>.AppImage'
Enter fullscreen mode Exit fullscreen mode

然后运行它

$ ./<You app>.AppImage
Enter fullscreen mode Exit fullscreen mode

如果再次遇到 4755 错误,则使用此命令:

$ sudo chown root '<Your appname>.AppImage' 
Enter fullscreen mode Exit fullscreen mode

然后

$ sudo chmod 4755 '<Your appname>.AppImage'   
Enter fullscreen mode Exit fullscreen mode

然后尝试再次运行它。

您还可以构建您喜欢类型的 Linux 应用程序,例如 Debian。

跟进

文章来源:https://dev.to/wchr/how-to-build-electron-apps-with-react-36b
PREV
Continue Using .env Files As Usual. 1) I can genuinely say I don't think I understand your first paragraph. 2) Sure, it takes some guts to say anything, I suppose. Although, I don't think it takes that much guts to type something on the Internet. That aside, the post would have been great if it had just been to the point, but instead it included a level of toxicity that wasn't necessary to make the point. That is what I commented on. I love sharing ideas and learning new things - I really do, but I can also do without the toxicity that is already so prevalent elsewhere on the Internet. It'd be nice if people as smart as software developers could get rid of the ape mind and just have an academic discussion or debate without taking pot shots that don't add anything.
NEXT
GPT Web App Generator - 让 AI 根据您的描述创建全栈 React 和 Node.js 代码库 🤖🤯