cnpm create vite
选择React => JavaScript =>cd react_vite => cnpm i =>npm run dev
二.安装Electron依赖
指定版本相对稳定
cnpm i [email protected] -D
cnpm i [email protected] -D
cnpm i [email protected] -D
三.创建electron目录
创建electron/index.js electron文件夹与src同级
index.js:
import { app, BrowserWindow, } from 'electron'
import path from "path"
let mainWin
const createWindow = () => {
mainWin = new BrowserWindow({
width: 800,
height: 500,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
})
if (process.env.NODE_ENV !== 'development') {
mainWin.loadFile(path.join(__dirname, "../index.html"))
} else {
// VITE_DEV_SERVER_HOST 如果是undefined 换成 VITE_DEV_SERVER_HOSTNAME
mainWin.loadURL(`http://${process.env['VITE_DEV_SERVER_HOSTNAME']}:${process.env['VITE_DEV_SERVER_PORT']}`)
}
}
app.whenReady().then(createWindow)
四.配置vite.config.js与package.json
vite.config.js:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import electron from 'vite-plugin-electron'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(), electron({
main: {
// 置顶 electron 入口文件
entry: "electron/index.js"
}
})],
})
package.json:
把 “type”:“module” 删除掉,添加 "main": "dist/electron/index.js", 指定入口文件
运行项目:npm run dev
打包:修改package.json配置
"build": "vite build && electron-builder",
添加build配置
{
"name": "react_vite",
"private": true,
"version": "0.0.0",
"main": "dist/electron/index.js",
"scripts": {
"dev": "vite",
"build": "vite build && electron-builder",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/react": "^18.0.28",
"@types/react-dom": "^18.0.11",
"@vitejs/plugin-react": "^3.1.0",
"electron": "^19.0.10",
"electron-builder": "^23.0.1",
"vite": "^4.2.0",
"vite-plugin-electron": "^0.9.3"
},
"build": {
"appId": "com.electron.desktop",
"productName": "electron",
"asar": false,
"copyright": "Copyright © 2022 electron",
"directories": {
"output": "release/"
},
"files": [
"dist"
],
"mac": {
"artifactName": "${productName}_${version}.${ext}",
"target": [
"dmg"
]
},
"win": {
"target": [
{
"target": "nsis",
"arch": [
"x64"
]
}
],
"artifactName": "${productName}_${version}.${ext}"
},
"nsis": {
"oneClick": false,
"perMachine": false,
"allowToChangeInstallationDirectory": true,
"deleteAppDataOnUninstall": false
},
"publish": [
{
"provider": "generic",
"url": "http://127.0.0.1:8080"
}
],
"releaseInfo": {
"releaseNotes": "版本更新的具体内容"
}
}
}
npm run build