如果我们的技术栈是react,也想要用electron来开发一个桌面的多端应用该怎么做呢?这篇文章选择了react的技术栈,讲解了环境的初始化步骤
实现效果
步骤
- 创建 react 项目
npm create vite@latest my-react-app
- 安装依赖
cd my-react-app
npm install
- 启动项目
npm run dev
浏览器能打开我们的 app 页面即可。
安装 electron
npm install electron -D
npm i electron-builder -D
注意:这两个依赖包是开发环境依赖,生产环境不需要安装。否则,后面打包应用会报错
完整的配置文件如下:
{
"name": "r18electronapp",
"private": true,
"version": "0.0.1",
"main": "./electron/main.js",
"description": "r18electronapp",
"author": "gf.r18electronapp",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview",
"ele:build": "vite build && electron-builder"
},
"build": {
"productName": "r18electronapp",
"appId": "gaofeng.r18electronapp",
"copyright": "gf.r18electronapp © 2024",
"compression": "maximum",
"asar": true,
"directories": {
"output": "release/"
},
"nsis": {
"oneClick": false,
"allowToChangeInstallationDirectory": true,
"perMachine": true,
"deleteAppDataOnUninstall": true,
"createDesktopShortcut": true,
"createStartMenuShortcut": true,
"shortcutName": "ElectronDeskTopTool"
},
"win": {
"icon": "./public/favicon.ico",
"artifactName": "${productName}-v${version}-${platform}-setup.${ext}",
"target": [
{
"target": "nsis"
}
]
},
"mac": {
"icon": "./public/favicon.ico",
"artifactName": "${productName}-v${version}-${platform}-setup.${ext}"
},
"linux": {
"icon": "./public/favicon.ico",
"artifactName": "${productName}-v${version}-${platform}-setup.${ext}"
}
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1",
"vite-plugin-electron": "^0.28.7"
},
"devDependencies": {
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.1",
"electron": "^31.3.1",
"electron-builder": "^24.13.3",
"eslint": "^8.57.0",
"eslint-plugin-react": "^7.34.3",
"eslint-plugin-react-hooks": "^4.6.2",
"eslint-plugin-react-refresh": "^0.4.7",
"vite": "^5.3.4",
"vite-plugin-electron-renderer": "^0.14.5"
}
}
如果报错,按提示安装即可。问题不大。
-
修改 packge.json
添加"main": "./electron/main.js",
,删除type:module
,添加desctiption
,添加author
-
创建 electron 目录
mkdir electron
- 创建 main.js
touch electron/main.js
touch electron/preload.js
增加.npmrc 配置
strict-ssl=false
registry=https://registry.npmmirror.com/
electron_mirror=https://registry.npmmirror.com/-/binary/electron/
electron_builder_binaries_mirror=https://registry.npmmirror.com/-/binary/electron-builder-binaries/
# ELECTRON_BUILDER_BINARIES_MIRROR=https://mirrors.huaweicloud.com/electron-builder-binaries/
配置 vite.config.js
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import electron from "vite-plugin-electron/simple";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react(),
electron({
main: {
// `build.lib.entry的快捷方式`
entry: "electron/main.js",
},
preload: {
//`build.rollupOptions.input的快捷方式`
input: "electron/preload.js",
},
// 可选:在渲染器进程中使用Node.js API
renderer: {},
}),
],
});
运行
npm run dev
打包应用
npm run ele:build