vite+react-ts+electron 开发桌面端

2022-03-16 08:41:48 浏览数 (1)

vite react-ts electron 开发桌面端

代码仓库

https://gitee.com/dmhsq/react-ts-vite-electron

https://github.com/promiseHusky/react-ts-vite-electron

vite搭建项目

npm init vite@latest my-electron

选择 react-ts

安装依赖包

代码语言:txt复制
npm i concurrently electron cross-env -D

创建main.js

代码语言:javascript复制
const { app, BrowserWindow } = require('electron');

class AppWindow extends BrowserWindow {
  constructor(config, urlLocation) {
    const basicConfig = {
      width: 800,
      height: 600,
      webPreferences: {
        contextIsolation: false,
        nodeIntegration: true,
        enableRemoteModule: true,
        nodeIntegrationInWorker: true,
      },
      show: false,
      backgroundColor: '#efefef',
    };
    const finalConfig = { ...basicConfig, ...config };
    super(finalConfig);
    this.loadURL(urlLocation);
    this.once('ready-to-show', () => {
      this.show();
    });
  }
}

app.on('ready', () => {
  const mainWindowConfig = {
    width: 1440,
    height: 768,
  };
  const urlLocation = 'http://localhost:3000';
  mainWindow = new AppWindow(mainWindowConfig, urlLocation);
  mainWindow.on('closed', () => {
    mainWindow = null;
    app.quit();
  });
});

配置package.json文件

代码语言:json复制
{
  "name": "my-electron",
  "private": true,
  "version": "0.0.0",
  "main": "main.js",
  "scripts": {
    "start": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview",
    "dev": "concurrently "electron ." "cross-env BROWSER=none vite""
  },
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  },
  "devDependencies": {
    "@types/react": "^17.0.33",
    "@types/react-dom": "^17.0.10",
    "@vitejs/plugin-react": "^1.0.7",
    "concurrently": "^7.0.0",
    "cross-env": "^7.0.3",
    "electron": "^17.1.2",
    "typescript": "^4.5.4",
    "vite": "^2.8.0"
  }
}

运行

执行 npm run dev即可运行

在这里插入图片描述在这里插入图片描述

关于打包

逻辑是

打包 react

打包 electron main.js 复制资源(logo.ico)

打包 electron

使用electron-builder

在这里插入图片描述在这里插入图片描述

0 人点赞