尝试使用Electron开发桌面应用程序
环境配置
- 运行命令
npm create vite .
- 运行命令
npm install
- 在src下新建一个ui文件夹,将原全部文件放入其中
- 删除public文件夹
- 修改
vite.config.ts
为:
1 2 3 4 5 6 7
| export default defineConfig({ plugins: [react()], base: './', build: { outDir: "dist-react", } })
|
1 2 3 4 5 6 7
| import { app, BrowserWindow } from 'electron'; import path from 'path'
app.on('ready', () => { const mainWindow = new BrowserWindow({}); mainWindow.loadFile(path.join(app.getAppPath(), '/dist-react/index.html')); });
|
1 2 3 4 5 6 7 8 9 10
| "type": "module", "main": "src/electron/main", "scripts": { "dev:react": "vite", "dev:electron": "electron .", "build": "tsc -b && vite build", "lint": "eslint .", "preview": "vite preview" },
|
然后运行”build”之后再运行”dev:electron”就可以看到窗口啦
(⊙o⊙)…
因为要使用Typescript,所以要做些修改,src/electron/tsconfig.json
创建文件,修改刚刚的文件为main.ts
,tsconfig.json
文件里面如下配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| { "compilerOptions": { "strict": true, "target": "ESNext", "module": "NodeNext", "outDir": "../../dist-electron", "skipLibCheck": true } }
|
修改package.json
如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| { "name": "electron-app", "private": true, "version": "0.0.0", "type": "module", "main": "dist-electron/main", "scripts": { "dev:react": "vite", "dev:electron": "electron .", "build": "tsc -b && vite build", "lint": "eslint .", "preview": "vite preview", "transpile:electron": "tsc --project src/electron/tsconfig.json" },
|
先运行npm run transpile:electron
再运行npm run dev:electron
可以得出相同结果
(ps:不要忘记修改.gitignore
)
1 2 3
| dist dist-react dist-electron
|
请在根目录下添加文件electron-builder.json
,以及对应的图片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| { "appId": "com.wood1208.electron-course", "files": ["dist-electron", "dist-react"], "icon": "./desktopIcon.png", "mac": { "target": "dmg" }, "linux": { "target": "AppImage", "category": "Utility" }, "win": { "target": ["portable", "msi"] } }
|
又修改package.json
文件 "main": "dist-electron/main.js"
添加命令:
1 2 3
| "dist:mac": "npm run transpile:electron && npm run build && electron-builder --mac --arm64", "dist:win": "npm run transpile:electron && npm run build && electron-builder --win --x64", "dist:linux": "npm run transpile:electron && npm run build && electron-builder --linux --x64"
|
喵的,构建这里也有下载问题,而且感觉不是很好解决,之后等我心情好点我再回来弄吧
ε=(´ο`*)))唉