├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── help_wanted.md ├── PULL_REQUEST_TEMPLATE.md ├── dependabot.yml └── workflows │ ├── build.yml │ └── ci.yml ├── .gitignore ├── .npmrc ├── .playwright.config.txt ├── .vite.config.flat.txt ├── .vscode ├── .debug.script.mjs ├── extensions.json ├── launch.json ├── settings.json └── tasks.json ├── LICENSE ├── README.md ├── README.zh-CN.md ├── build ├── icon.icns ├── icon.ico └── icon.png ├── electron-builder.json ├── electron-vite-react-debug.gif ├── electron-vite-react.gif ├── electron ├── electron-env.d.ts ├── main │ ├── index.ts │ └── update.ts └── preload │ └── index.ts ├── index.html ├── package.json ├── postcss.config.cjs ├── public ├── favicon.ico └── node.svg ├── src ├── App.css ├── App.tsx ├── assets │ ├── logo-electron.svg │ ├── logo-v1.svg │ └── logo-vite.svg ├── components │ └── update │ │ ├── Modal │ │ ├── index.tsx │ │ └── modal.css │ │ ├── Progress │ │ ├── index.tsx │ │ └── progress.css │ │ ├── README.md │ │ ├── README.zh-CN.md │ │ ├── index.tsx │ │ └── update.css ├── demos │ ├── ipc.ts │ └── node.ts ├── index.css ├── main.tsx ├── type │ └── electron-updater.d.ts └── vite-env.d.ts ├── tailwind.config.js ├── test ├── e2e.spec.ts └── screenshots │ └── e2e.png ├── tsconfig.json ├── tsconfig.node.json ├── vite.config.ts └── vitest.config.ts /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | name: 🐞 Bug report 4 | about: Create a report to help us improve 5 | title: "[Bug] the title of bug report" 6 | labels: bug 7 | assignees: '' 8 | 9 | --- 10 | 11 | #### Describe the bug 12 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/help_wanted.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🥺 Help wanted 3 | about: Confuse about the use of electron-vue-vite 4 | title: "[Help] the title of help wanted report" 5 | labels: help wanted 6 | assignees: '' 7 | 8 | --- 9 | 10 | #### Describe the problem you confuse 11 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ### Description 4 | 5 | 6 | 7 | ### What is the purpose of this pull request? 8 | 9 | - [ ] Bug fix 10 | - [ ] New Feature 11 | - [ ] Documentation update 12 | - [ ] Other 13 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "npm" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "monthly" 12 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | paths-ignore: 7 | - "**.md" 8 | - "**.spec.js" 9 | - ".idea" 10 | - ".vscode" 11 | - ".dockerignore" 12 | - "Dockerfile" 13 | - ".gitignore" 14 | - ".github/**" 15 | - "!.github/workflows/build.yml" 16 | 17 | jobs: 18 | build: 19 | runs-on: ${{ matrix.os }} 20 | 21 | strategy: 22 | matrix: 23 | os: [macos-latest, ubuntu-latest, windows-latest] 24 | 25 | steps: 26 | - name: Checkout Code 27 | uses: actions/checkout@v3 28 | 29 | - name: Setup Node.js 30 | uses: actions/setup-node@v3 31 | with: 32 | node-version: 18 33 | 34 | - name: Install Dependencies 35 | run: npm install 36 | 37 | - name: Build Release Files 38 | run: npm run build 39 | env: 40 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 41 | 42 | - name: Upload Artifact 43 | uses: actions/upload-artifact@v3 44 | with: 45 | name: release_on_${{ matrix. os }} 46 | path: release/ 47 | retention-days: 5 -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | pull_request_target: 5 | branches: 6 | - main 7 | 8 | permissions: 9 | pull-requests: write 10 | 11 | jobs: 12 | job1: 13 | name: Check Not Allowed File Changes 14 | runs-on: ubuntu-latest 15 | outputs: 16 | markdown_change: ${{ steps.filter_markdown.outputs.change }} 17 | markdown_files: ${{ steps.filter_markdown.outputs.change_files }} 18 | steps: 19 | 20 | - name: Check Not Allowed File Changes 21 | uses: dorny/paths-filter@v2 22 | id: filter_not_allowed 23 | with: 24 | list-files: json 25 | filters: | 26 | change: 27 | - 'package-lock.json' 28 | - 'yarn.lock' 29 | - 'pnpm-lock.yaml' 30 | 31 | # ref: https://github.com/github/docs/blob/main/.github/workflows/triage-unallowed-contributions.yml 32 | - name: Comment About Changes We Can't Accept 33 | if: ${{ steps.filter_not_allowed.outputs.change == 'true' }} 34 | uses: actions/github-script@v6 35 | with: 36 | script: | 37 | let workflowFailMessage = "It looks like you've modified some files that we can't accept as contributions." 38 | try { 39 | const badFilesArr = [ 40 | 'package-lock.json', 41 | 'yarn.lock', 42 | 'pnpm-lock.yaml', 43 | ] 44 | const badFiles = badFilesArr.join('\n- ') 45 | const reviewMessage = `👋 Hey there spelunker. It looks like you've modified some files that we can't accept as contributions. The complete list of files we can't accept are:\n- ${badFiles}\n\nYou'll need to revert all of the files you changed in that list using [GitHub Desktop](https://docs.github.com/en/free-pro-team@latest/desktop/contributing-and-collaborating-using-github-desktop/managing-commits/reverting-a-commit) or \`git checkout origin/main \`. Once you get those files reverted, we can continue with the review process. :octocat:\n\nMore discussion:\n- https://github.com/electron-vite/electron-vite-vue/issues/192` 46 | createdComment = await github.rest.issues.createComment({ 47 | owner: context.repo.owner, 48 | repo: context.repo.repo, 49 | issue_number: context.payload.number, 50 | body: reviewMessage, 51 | }) 52 | workflowFailMessage = `${workflowFailMessage} Please see ${createdComment.data.html_url} for details.` 53 | } catch(err) { 54 | console.log("Error creating comment.", err) 55 | } 56 | core.setFailed(workflowFailMessage) 57 | 58 | - name: Check Not Linted Markdown 59 | if: ${{ always() }} 60 | uses: dorny/paths-filter@v2 61 | id: filter_markdown 62 | with: 63 | list-files: shell 64 | filters: | 65 | change: 66 | - added|modified: '*.md' 67 | 68 | 69 | job2: 70 | name: Lint Markdown 71 | runs-on: ubuntu-latest 72 | needs: job1 73 | if: ${{ always() && needs.job1.outputs.markdown_change == 'true' }} 74 | steps: 75 | - name: Checkout Code 76 | uses: actions/checkout@v3 77 | with: 78 | ref: ${{ github.event.pull_request.head.sha }} 79 | 80 | - name: Lint markdown 81 | run: npx markdownlint-cli ${{ needs.job1.outputs.markdown_files }} --ignore node_modules -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | dist-electron 14 | release 15 | *.local 16 | 17 | # Editor directories and files 18 | .vscode/.debug.env 19 | .idea 20 | .DS_Store 21 | *.suo 22 | *.ntvs* 23 | *.njsproj 24 | *.sln 25 | *.sw? 26 | 27 | #lockfile 28 | package-lock.json 29 | pnpm-lock.yaml 30 | yarn.lock 31 | /test-results/ 32 | /playwright-report/ 33 | /playwright/.cache/ 34 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | # For electron-builder 2 | # https://github.com/electron-userland/electron-builder/issues/6289#issuecomment-1042620422 3 | shamefully-hoist=true 4 | 5 | # For China 🇨🇳 developers 6 | # electron_mirror=https://npmmirror.com/mirrors/electron/ 7 | -------------------------------------------------------------------------------- /.playwright.config.txt: -------------------------------------------------------------------------------- 1 | import type { PlaywrightTestConfig } from "@playwright/test"; 2 | 3 | /** 4 | * Read environment variables from file. 5 | * https://github.com/motdotla/dotenv 6 | */ 7 | // require('dotenv').config(); 8 | 9 | /** 10 | * See https://playwright.dev/docs/test-configuration. 11 | */ 12 | const config: PlaywrightTestConfig = { 13 | testDir: "./e2e", 14 | /* Maximum time one test can run for. */ 15 | timeout: 30 * 1000, 16 | expect: { 17 | /** 18 | * Maximum time expect() should wait for the condition to be met. 19 | * For example in `await expect(locator).toHaveText();` 20 | */ 21 | timeout: 5000, 22 | }, 23 | /* Run tests in files in parallel */ 24 | fullyParallel: true, 25 | /* Fail the build on CI if you accidentally left test.only in the source code. */ 26 | forbidOnly: !!process.env.CI, 27 | /* Retry on CI only */ 28 | retries: process.env.CI ? 2 : 0, 29 | /* Opt out of parallel tests on CI. */ 30 | workers: process.env.CI ? 1 : undefined, 31 | /* Reporter to use. See https://playwright.dev/docs/test-reporters */ 32 | reporter: "html", 33 | /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ 34 | use: { 35 | /* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */ 36 | actionTimeout: 0, 37 | /* Base URL to use in actions like `await page.goto('/')`. */ 38 | // baseURL: 'http://localhost:3000', 39 | 40 | /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ 41 | trace: "on-first-retry", 42 | }, 43 | 44 | /* Folder for test artifacts such as screenshots, videos, traces, etc. */ 45 | // outputDir: 'test-results/', 46 | 47 | /* Run your local dev server before starting the tests */ 48 | // webServer: { 49 | // command: 'npm run start', 50 | // port: 3000, 51 | // }, 52 | }; 53 | 54 | export default config; 55 | -------------------------------------------------------------------------------- /.vite.config.flat.txt: -------------------------------------------------------------------------------- 1 | import { rmSync } from 'node:fs' 2 | import path from 'node:path' 3 | import { defineConfig } from 'vite' 4 | import react from '@vitejs/plugin-react' 5 | import electron from 'vite-plugin-electron' 6 | import renderer from 'vite-plugin-electron-renderer' 7 | import pkg from './package.json' 8 | 9 | // https://vitejs.dev/config/ 10 | export default defineConfig(({ command }) => { 11 | rmSync('dist-electron', { recursive: true, force: true }) 12 | 13 | const isServe = command === 'serve' 14 | const isBuild = command === 'build' 15 | const sourcemap = isServe || !!process.env.VSCODE_DEBUG 16 | 17 | return { 18 | resolve: { 19 | alias: { 20 | '@': path.join(__dirname, 'src') 21 | }, 22 | }, 23 | plugins: [ 24 | react(), 25 | electron([ 26 | { 27 | // Main-Process entry file of the Electron App. 28 | entry: 'electron/main/index.ts', 29 | onstart(options) { 30 | if (process.env.VSCODE_DEBUG) { 31 | console.log(/* For `.vscode/.debug.script.mjs` */'[startup] Electron App') 32 | } else { 33 | options.startup() 34 | } 35 | }, 36 | vite: { 37 | build: { 38 | sourcemap, 39 | minify: isBuild, 40 | outDir: 'dist-electron/main', 41 | rollupOptions: { 42 | external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}), 43 | }, 44 | }, 45 | }, 46 | }, 47 | { 48 | entry: 'electron/preload/index.ts', 49 | onstart(options) { 50 | // Notify the Renderer-Process to reload the page when the Preload-Scripts build is complete, 51 | // instead of restarting the entire Electron App. 52 | options.reload() 53 | }, 54 | vite: { 55 | build: { 56 | sourcemap: sourcemap ? 'inline' : undefined, // #332 57 | minify: isBuild, 58 | outDir: 'dist-electron/preload', 59 | rollupOptions: { 60 | external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}), 61 | }, 62 | }, 63 | }, 64 | } 65 | ]), 66 | // Use Node.js API in the Renderer-process 67 | renderer(), 68 | ], 69 | server: process.env.VSCODE_DEBUG && (() => { 70 | const url = new URL(pkg.debug.env.VITE_DEV_SERVER_URL) 71 | return { 72 | host: url.hostname, 73 | port: +url.port, 74 | } 75 | })(), 76 | clearScreen: false, 77 | } 78 | }) 79 | -------------------------------------------------------------------------------- /.vscode/.debug.script.mjs: -------------------------------------------------------------------------------- 1 | import fs from 'node:fs' 2 | import path from 'node:path' 3 | import { fileURLToPath } from 'node:url' 4 | import { createRequire } from 'node:module' 5 | import { spawn } from 'node:child_process' 6 | 7 | const pkg = createRequire(import.meta.url)('../package.json') 8 | const __dirname = path.dirname(fileURLToPath(import.meta.url)) 9 | 10 | // write .debug.env 11 | const envContent = Object.entries(pkg.debug.env).map(([key, val]) => `${key}=${val}`) 12 | fs.writeFileSync(path.join(__dirname, '.debug.env'), envContent.join('\n')) 13 | 14 | // bootstrap 15 | spawn( 16 | // TODO: terminate `npm run dev` when Debug exits. 17 | process.platform === 'win32' ? 'npm.cmd' : 'npm', 18 | ['run', 'dev'], 19 | { 20 | stdio: 'inherit', 21 | env: Object.assign(process.env, { VSCODE_DEBUG: 'true' }), 22 | }, 23 | ) -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // See http://go.microsoft.com/fwlink/?LinkId=827846 3 | // for the documentation about the extensions.json format 4 | "recommendations": [ 5 | "mrmlnc.vscode-json5" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "compounds": [ 7 | { 8 | "name": "Debug App", 9 | "preLaunchTask": "Before Debug", 10 | "configurations": [ 11 | "Debug Main Process", 12 | "Debug Renderer Process" 13 | ], 14 | "presentation": { 15 | "hidden": false, 16 | "group": "", 17 | "order": 1 18 | }, 19 | "stopAll": true 20 | } 21 | ], 22 | "configurations": [ 23 | { 24 | "name": "Debug Main Process", 25 | "type": "node", 26 | "request": "launch", 27 | "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron", 28 | "windows": { 29 | "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron.cmd" 30 | }, 31 | "runtimeArgs": [ 32 | "--no-sandbox", 33 | "--remote-debugging-port=9229", 34 | "." 35 | ], 36 | "envFile": "${workspaceFolder}/.vscode/.debug.env", 37 | "console": "integratedTerminal" 38 | }, 39 | { 40 | "name": "Debug Renderer Process", 41 | "port": 9229, 42 | "request": "attach", 43 | "type": "chrome", 44 | "timeout": 60000, 45 | "skipFiles": [ 46 | "/**", 47 | "${workspaceRoot}/node_modules/**", 48 | "${workspaceRoot}/dist-electron/**", 49 | // Skip files in host(VITE_DEV_SERVER_URL) 50 | "http://127.0.0.1:7777/**" 51 | ] 52 | }, 53 | ] 54 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "typescript.tsdk": "node_modules/typescript/lib", 3 | "typescript.tsc.autoDetect": "off", 4 | "json.schemas": [ 5 | { 6 | "fileMatch": [ 7 | "/*electron-builder.json5", 8 | "/*electron-builder.json" 9 | ], 10 | "url": "https://json.schemastore.org/electron-builder" 11 | } 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "label": "Before Debug", 8 | "type": "shell", 9 | "command": "node .vscode/.debug.script.mjs", 10 | "isBackground": true, 11 | "problemMatcher": { 12 | "owner": "typescript", 13 | "fileLocation": "relative", 14 | "pattern": { 15 | // TODO: correct "regexp" 16 | "regexp": "^([a-zA-Z]\\:\/?([\\w\\-]\/?)+\\.\\w+):(\\d+):(\\d+): (ERROR|WARNING)\\: (.*)$", 17 | "file": 1, 18 | "line": 3, 19 | "column": 4, 20 | "code": 5, 21 | "message": 6 22 | }, 23 | "background": { 24 | "activeOnStart": true, 25 | "beginsPattern": "^.*VITE v.* ready in \\d* ms.*$", 26 | "endsPattern": "^.*\\[startup\\] Electron App.*$" 27 | } 28 | } 29 | } 30 | ] 31 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 草鞋没号 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # electron-vite-react 2 | 3 | [![awesome-vite](https://awesome.re/mentioned-badge.svg)](https://github.com/vitejs/awesome-vite) 4 | ![GitHub stars](https://img.shields.io/github/stars/caoxiemeihao/vite-react-electron?color=fa6470) 5 | ![GitHub issues](https://img.shields.io/github/issues/caoxiemeihao/vite-react-electron?color=d8b22d) 6 | ![GitHub license](https://img.shields.io/github/license/caoxiemeihao/vite-react-electron) 7 | [![Required Node.JS >= 14.18.0 || >=16.0.0](https://img.shields.io/static/v1?label=node&message=14.18.0%20||%20%3E=16.0.0&logo=node.js&color=3f893e)](https://nodejs.org/about/releases) 8 | 9 | English | [简体中文](README.zh-CN.md) 10 | 11 | ## 👀 Overview 12 | 13 | 📦 Ready out of the box 14 | 🎯 Based on the official [template-react-ts](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts), project structure will be familiar to you 15 | 🌱 Easily extendable and customizable 16 | 💪 Supports Node.js API in the renderer process 17 | 🔩 Supports C/C++ native addons 18 | 🐞 Debugger configuration included 19 | 🖥 Easy to implement multiple windows 20 | 21 | ## 🛫 Quick Setup 22 | 23 | ```sh 24 | # clone the project 25 | git clone https://github.com/electron-vite/electron-vite-react.git 26 | 27 | # enter the project directory 28 | cd electron-vite-react 29 | 30 | # install dependency 31 | npm install 32 | 33 | # develop 34 | npm run dev 35 | ``` 36 | 37 | ## 🐞 Debug 38 | 39 | ![electron-vite-react-debug.gif](/electron-vite-react-debug.gif) 40 | 41 | ## 📂 Directory structure 42 | 43 | Familiar React application structure, just with `electron` folder on the top :wink: 44 | *Files in this folder will be separated from your React application and built into `dist-electron`* 45 | 46 | ```tree 47 | ├── electron Electron-related code 48 | │ ├── main Main-process source code 49 | │ └── preload Preload-scripts source code 50 | │ 51 | ├── release Generated after production build, contains executables 52 | │ └── {version} 53 | │ ├── {os}-{os_arch} Contains unpacked application executable 54 | │ └── {app_name}_{version}.{ext} Installer for the application 55 | │ 56 | ├── public Static assets 57 | └── src Renderer source code, your React application 58 | ``` 59 | 60 | 82 | 83 | ## 🔧 Additional features 84 | 85 | 1. electron-updater 👉 [see docs](src/components/update/README.md) 86 | 1. playwright 87 | 88 | ## ❔ FAQ 89 | 90 | - [C/C++ addons, Node.js modules - Pre-Bundling](https://github.com/electron-vite/vite-plugin-electron-renderer#dependency-pre-bundling) 91 | - [dependencies vs devDependencies](https://github.com/electron-vite/vite-plugin-electron-renderer#dependencies-vs-devdependencies) 92 | -------------------------------------------------------------------------------- /README.zh-CN.md: -------------------------------------------------------------------------------- 1 | # vite-react-electron 2 | 3 | [![awesome-vite](https://awesome.re/mentioned-badge.svg)](https://github.com/vitejs/awesome-vite) 4 | ![GitHub stars](https://img.shields.io/github/stars/caoxiemeihao/vite-react-electron?color=fa6470) 5 | ![GitHub issues](https://img.shields.io/github/issues/caoxiemeihao/vite-react-electron?color=d8b22d) 6 | ![GitHub license](https://img.shields.io/github/license/caoxiemeihao/vite-react-electron) 7 | [![Required Node.JS >= 14.18.0 || >=16.0.0](https://img.shields.io/static/v1?label=node&message=14.18.0%20||%20%3E=16.0.0&logo=node.js&color=3f893e)](https://nodejs.org/about/releases) 8 | 9 | [English](README.md) | 简体中文 10 | 11 | ## 概述 12 | 13 | 📦 开箱即用 14 | 🎯 基于官方的 [template-react-ts](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts), 低侵入性 15 | 🌱 结构清晰,可塑性强 16 | 💪 支持在渲染进程中使用 Electron、Node.js API 17 | 🔩 支持 C/C++ 模块 18 | 🖥 很容易实现多窗口 19 | 20 | ## 快速开始 21 | 22 | ```sh 23 | # clone the project 24 | git clone https://github.com/electron-vite/electron-vite-react.git 25 | 26 | # enter the project directory 27 | cd electron-vite-react 28 | 29 | # install dependency 30 | npm install 31 | 32 | # develop 33 | npm run dev 34 | ``` 35 | 36 | ## 调试 37 | 38 | ![electron-vite-react-debug.gif](/electron-vite-react-debug.gif) 39 | 40 | ## 目录 41 | 42 | *🚨 默认情况下, `electron` 文件夹下的文件将会被构建到 `dist-electron`* 43 | 44 | ```tree 45 | ├── electron Electron 源码文件夹 46 | │ ├── main Main-process 源码 47 | │ └── preload Preload-scripts 源码 48 | │ 49 | ├── release 构建后生成程序目录 50 | │ └── {version} 51 | │ ├── {os}-{os_arch} 未打包的程序(绿色运行版) 52 | │ └── {app_name}_{version}.{ext} 应用安装文件 53 | │ 54 | ├── public 同 Vite 模板的 public 55 | └── src 渲染进程源码、React代码 56 | ``` 57 | 58 | 78 | 79 | ## 🔧 额外的功能 80 | 81 | 1. Electron 自动更新 👉 [阅读文档](src/components/update/README.zh-CN.md) 82 | 2. Playwright 测试 83 | 84 | ## ❔ FAQ 85 | 86 | - [C/C++ addons, Node.js modules - Pre-Bundling](https://github.com/electron-vite/vite-plugin-electron-renderer#dependency-pre-bundling) 87 | - [dependencies vs devDependencies](https://github.com/electron-vite/vite-plugin-electron-renderer#dependencies-vs-devdependencies) 88 | 89 | ## 🍵 🍰 🍣 🍟 90 | 91 | 92 | -------------------------------------------------------------------------------- /build/icon.icns: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowman074/electron-vite-react/23537c8fed330749e0c7c625ee0273c82a4a7ed5/build/icon.icns -------------------------------------------------------------------------------- /build/icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowman074/electron-vite-react/23537c8fed330749e0c7c625ee0273c82a4a7ed5/build/icon.ico -------------------------------------------------------------------------------- /build/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowman074/electron-vite-react/23537c8fed330749e0c7c625ee0273c82a4a7ed5/build/icon.png -------------------------------------------------------------------------------- /electron-builder.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://raw.githubusercontent.com/electron-userland/electron-builder/master/packages/app-builder-lib/scheme.json", 3 | "appId": "YourAppID", 4 | "asar": true, 5 | "directories": { 6 | "output": "release/${version}" 7 | }, 8 | "files": [ 9 | "dist-electron", 10 | "dist" 11 | ], 12 | "mac": { 13 | "artifactName": "${productName}_${version}.${ext}", 14 | "target": [ 15 | "dmg", 16 | "zip" 17 | ] 18 | }, 19 | "win": { 20 | "target": [ 21 | { 22 | "target": "nsis", 23 | "arch": [ 24 | "x64" 25 | ] 26 | } 27 | ], 28 | "artifactName": "${productName}_${version}.${ext}" 29 | }, 30 | "nsis": { 31 | "oneClick": false, 32 | "perMachine": false, 33 | "allowToChangeInstallationDirectory": true, 34 | "deleteAppDataOnUninstall": false 35 | }, 36 | "publish": { 37 | "provider": "generic", 38 | "channel": "latest", 39 | "url": "https://github.com/electron-vite/electron-vite-react/releases/download/v0.9.9/" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /electron-vite-react-debug.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowman074/electron-vite-react/23537c8fed330749e0c7c625ee0273c82a4a7ed5/electron-vite-react-debug.gif -------------------------------------------------------------------------------- /electron-vite-react.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowman074/electron-vite-react/23537c8fed330749e0c7c625ee0273c82a4a7ed5/electron-vite-react.gif -------------------------------------------------------------------------------- /electron/electron-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | declare namespace NodeJS { 4 | interface ProcessEnv { 5 | VSCODE_DEBUG?: 'true' 6 | /** 7 | * The built directory structure 8 | * 9 | * ```tree 10 | * ├─┬ dist-electron 11 | * │ ├─┬ main 12 | * │ │ └── index.js > Electron-Main 13 | * │ └─┬ preload 14 | * │ └── index.mjs > Preload-Scripts 15 | * ├─┬ dist 16 | * │ └── index.html > Electron-Renderer 17 | * ``` 18 | */ 19 | APP_ROOT: string 20 | /** /dist/ or /public/ */ 21 | VITE_PUBLIC: string 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /electron/main/index.ts: -------------------------------------------------------------------------------- 1 | import { app, BrowserWindow, shell, ipcMain } from 'electron' 2 | import { createRequire } from 'node:module' 3 | import { fileURLToPath } from 'node:url' 4 | import path from 'node:path' 5 | import os from 'node:os' 6 | import { update } from './update' 7 | 8 | const require = createRequire(import.meta.url) 9 | const __dirname = path.dirname(fileURLToPath(import.meta.url)) 10 | 11 | // The built directory structure 12 | // 13 | // ├─┬ dist-electron 14 | // │ ├─┬ main 15 | // │ │ └── index.js > Electron-Main 16 | // │ └─┬ preload 17 | // │ └── index.mjs > Preload-Scripts 18 | // ├─┬ dist 19 | // │ └── index.html > Electron-Renderer 20 | // 21 | process.env.APP_ROOT = path.join(__dirname, '../..') 22 | 23 | export const MAIN_DIST = path.join(process.env.APP_ROOT, 'dist-electron') 24 | export const RENDERER_DIST = path.join(process.env.APP_ROOT, 'dist') 25 | export const VITE_DEV_SERVER_URL = process.env.VITE_DEV_SERVER_URL 26 | 27 | process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL 28 | ? path.join(process.env.APP_ROOT, 'public') 29 | : RENDERER_DIST 30 | 31 | // Disable GPU Acceleration for Windows 7 32 | if (os.release().startsWith('6.1')) app.disableHardwareAcceleration() 33 | 34 | // Set application name for Windows 10+ notifications 35 | if (process.platform === 'win32') app.setAppUserModelId(app.getName()) 36 | 37 | if (!app.requestSingleInstanceLock()) { 38 | app.quit() 39 | process.exit(0) 40 | } 41 | 42 | let win: BrowserWindow | null = null 43 | const preload = path.join(__dirname, '../preload/index.mjs') 44 | const indexHtml = path.join(RENDERER_DIST, 'index.html') 45 | 46 | async function createWindow() { 47 | win = new BrowserWindow({ 48 | title: 'Main window', 49 | icon: path.join(process.env.VITE_PUBLIC, 'favicon.ico'), 50 | webPreferences: { 51 | preload, 52 | // Warning: Enable nodeIntegration and disable contextIsolation is not secure in production 53 | // nodeIntegration: true, 54 | 55 | // Consider using contextBridge.exposeInMainWorld 56 | // Read more on https://www.electronjs.org/docs/latest/tutorial/context-isolation 57 | // contextIsolation: false, 58 | }, 59 | }) 60 | 61 | if (VITE_DEV_SERVER_URL) { // #298 62 | win.loadURL(VITE_DEV_SERVER_URL) 63 | // Open devTool if the app is not packaged 64 | win.webContents.openDevTools() 65 | } else { 66 | win.loadFile(indexHtml) 67 | } 68 | 69 | // Test actively push message to the Electron-Renderer 70 | win.webContents.on('did-finish-load', () => { 71 | win?.webContents.send('main-process-message', new Date().toLocaleString()) 72 | }) 73 | 74 | // Make all links open with the browser, not with the application 75 | win.webContents.setWindowOpenHandler(({ url }) => { 76 | if (url.startsWith('https:')) shell.openExternal(url) 77 | return { action: 'deny' } 78 | }) 79 | 80 | // Auto update 81 | update(win) 82 | } 83 | 84 | app.whenReady().then(createWindow) 85 | 86 | app.on('window-all-closed', () => { 87 | win = null 88 | if (process.platform !== 'darwin') app.quit() 89 | }) 90 | 91 | app.on('second-instance', () => { 92 | if (win) { 93 | // Focus on the main window if the user tried to open another 94 | if (win.isMinimized()) win.restore() 95 | win.focus() 96 | } 97 | }) 98 | 99 | app.on('activate', () => { 100 | const allWindows = BrowserWindow.getAllWindows() 101 | if (allWindows.length) { 102 | allWindows[0].focus() 103 | } else { 104 | createWindow() 105 | } 106 | }) 107 | 108 | // New window example arg: new windows url 109 | ipcMain.handle('open-win', (_, arg) => { 110 | const childWindow = new BrowserWindow({ 111 | webPreferences: { 112 | preload, 113 | nodeIntegration: true, 114 | contextIsolation: false, 115 | }, 116 | }) 117 | 118 | if (VITE_DEV_SERVER_URL) { 119 | childWindow.loadURL(`${VITE_DEV_SERVER_URL}#${arg}`) 120 | } else { 121 | childWindow.loadFile(indexHtml, { hash: arg }) 122 | } 123 | }) 124 | -------------------------------------------------------------------------------- /electron/main/update.ts: -------------------------------------------------------------------------------- 1 | import { app, ipcMain } from 'electron' 2 | import { createRequire } from 'node:module' 3 | import type { 4 | ProgressInfo, 5 | UpdateDownloadedEvent, 6 | UpdateInfo, 7 | } from 'electron-updater' 8 | 9 | const { autoUpdater } = createRequire(import.meta.url)('electron-updater'); 10 | 11 | export function update(win: Electron.BrowserWindow) { 12 | 13 | // When set to false, the update download will be triggered through the API 14 | autoUpdater.autoDownload = false 15 | autoUpdater.disableWebInstaller = false 16 | autoUpdater.allowDowngrade = false 17 | 18 | // start check 19 | autoUpdater.on('checking-for-update', function () { }) 20 | // update available 21 | autoUpdater.on('update-available', (arg: UpdateInfo) => { 22 | win.webContents.send('update-can-available', { update: true, version: app.getVersion(), newVersion: arg?.version }) 23 | }) 24 | // update not available 25 | autoUpdater.on('update-not-available', (arg: UpdateInfo) => { 26 | win.webContents.send('update-can-available', { update: false, version: app.getVersion(), newVersion: arg?.version }) 27 | }) 28 | 29 | // Checking for updates 30 | ipcMain.handle('check-update', async () => { 31 | if (!app.isPackaged) { 32 | const error = new Error('The update feature is only available after the package.') 33 | return { message: error.message, error } 34 | } 35 | 36 | try { 37 | return await autoUpdater.checkForUpdatesAndNotify() 38 | } catch (error) { 39 | return { message: 'Network error', error } 40 | } 41 | }) 42 | 43 | // Start downloading and feedback on progress 44 | ipcMain.handle('start-download', (event: Electron.IpcMainInvokeEvent) => { 45 | startDownload( 46 | (error, progressInfo) => { 47 | if (error) { 48 | // feedback download error message 49 | event.sender.send('update-error', { message: error.message, error }) 50 | } else { 51 | // feedback update progress message 52 | event.sender.send('download-progress', progressInfo) 53 | } 54 | }, 55 | () => { 56 | // feedback update downloaded message 57 | event.sender.send('update-downloaded') 58 | } 59 | ) 60 | }) 61 | 62 | // Install now 63 | ipcMain.handle('quit-and-install', () => { 64 | autoUpdater.quitAndInstall(false, true) 65 | }) 66 | } 67 | 68 | function startDownload( 69 | callback: (error: Error | null, info: ProgressInfo | null) => void, 70 | complete: (event: UpdateDownloadedEvent) => void, 71 | ) { 72 | autoUpdater.on('download-progress', (info: ProgressInfo) => callback(null, info)) 73 | autoUpdater.on('error', (error: Error) => callback(error, null)) 74 | autoUpdater.on('update-downloaded', complete) 75 | autoUpdater.downloadUpdate() 76 | } 77 | -------------------------------------------------------------------------------- /electron/preload/index.ts: -------------------------------------------------------------------------------- 1 | import { ipcRenderer, contextBridge } from 'electron' 2 | 3 | // --------- Expose some API to the Renderer process --------- 4 | contextBridge.exposeInMainWorld('ipcRenderer', { 5 | on(...args: Parameters) { 6 | const [channel, listener] = args 7 | return ipcRenderer.on(channel, (event, ...args) => listener(event, ...args)) 8 | }, 9 | off(...args: Parameters) { 10 | const [channel, ...omit] = args 11 | return ipcRenderer.off(channel, ...omit) 12 | }, 13 | send(...args: Parameters) { 14 | const [channel, ...omit] = args 15 | return ipcRenderer.send(channel, ...omit) 16 | }, 17 | invoke(...args: Parameters) { 18 | const [channel, ...omit] = args 19 | return ipcRenderer.invoke(channel, ...omit) 20 | }, 21 | 22 | // You can expose other APTs you need here. 23 | // ... 24 | }) 25 | 26 | // --------- Preload scripts loading --------- 27 | function domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) { 28 | return new Promise(resolve => { 29 | if (condition.includes(document.readyState)) { 30 | resolve(true) 31 | } else { 32 | document.addEventListener('readystatechange', () => { 33 | if (condition.includes(document.readyState)) { 34 | resolve(true) 35 | } 36 | }) 37 | } 38 | }) 39 | } 40 | 41 | const safeDOM = { 42 | append(parent: HTMLElement, child: HTMLElement) { 43 | if (!Array.from(parent.children).find(e => e === child)) { 44 | return parent.appendChild(child) 45 | } 46 | }, 47 | remove(parent: HTMLElement, child: HTMLElement) { 48 | if (Array.from(parent.children).find(e => e === child)) { 49 | return parent.removeChild(child) 50 | } 51 | }, 52 | } 53 | 54 | /** 55 | * https://tobiasahlin.com/spinkit 56 | * https://connoratherton.com/loaders 57 | * https://projects.lukehaas.me/css-loaders 58 | * https://matejkustec.github.io/SpinThatShit 59 | */ 60 | function useLoading() { 61 | const className = `loaders-css__square-spin` 62 | const styleContent = ` 63 | @keyframes square-spin { 64 | 25% { transform: perspective(100px) rotateX(180deg) rotateY(0); } 65 | 50% { transform: perspective(100px) rotateX(180deg) rotateY(180deg); } 66 | 75% { transform: perspective(100px) rotateX(0) rotateY(180deg); } 67 | 100% { transform: perspective(100px) rotateX(0) rotateY(0); } 68 | } 69 | .${className} > div { 70 | animation-fill-mode: both; 71 | width: 50px; 72 | height: 50px; 73 | background: #fff; 74 | animation: square-spin 3s 0s cubic-bezier(0.09, 0.57, 0.49, 0.9) infinite; 75 | } 76 | .app-loading-wrap { 77 | position: fixed; 78 | top: 0; 79 | left: 0; 80 | width: 100vw; 81 | height: 100vh; 82 | display: flex; 83 | align-items: center; 84 | justify-content: center; 85 | background: #282c34; 86 | z-index: 9; 87 | } 88 | ` 89 | const oStyle = document.createElement('style') 90 | const oDiv = document.createElement('div') 91 | 92 | oStyle.id = 'app-loading-style' 93 | oStyle.innerHTML = styleContent 94 | oDiv.className = 'app-loading-wrap' 95 | oDiv.innerHTML = `
` 96 | 97 | return { 98 | appendLoading() { 99 | safeDOM.append(document.head, oStyle) 100 | safeDOM.append(document.body, oDiv) 101 | }, 102 | removeLoading() { 103 | safeDOM.remove(document.head, oStyle) 104 | safeDOM.remove(document.body, oDiv) 105 | }, 106 | } 107 | } 108 | 109 | // ---------------------------------------------------------------------- 110 | 111 | const { appendLoading, removeLoading } = useLoading() 112 | domReady().then(appendLoading) 113 | 114 | window.onmessage = (ev) => { 115 | ev.data.payload === 'removeLoading' && removeLoading() 116 | } 117 | 118 | setTimeout(removeLoading, 4999) -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Electron + Vite + React 9 | 10 | 11 |
12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "electron-vite-react", 3 | "version": "2.2.0", 4 | "main": "dist-electron/main/index.js", 5 | "description": "Electron Vite React boilerplate.", 6 | "author": "草鞋没号 <308487730@qq.com>", 7 | "license": "MIT", 8 | "private": true, 9 | "debug": { 10 | "env": { 11 | "VITE_DEV_SERVER_URL": "http://127.0.0.1:7777/" 12 | } 13 | }, 14 | "type": "module", 15 | "scripts": { 16 | "dev": "vite", 17 | "build": "tsc && vite build && electron-builder", 18 | "preview": "vite preview", 19 | "pretest": "vite build --mode=test", 20 | "test": "vitest run" 21 | }, 22 | "dependencies": { 23 | "electron-updater": "^6.3.9" 24 | }, 25 | "devDependencies": { 26 | "@playwright/test": "^1.48.2", 27 | "@types/react": "^18.3.12", 28 | "@types/react-dom": "^18.3.1", 29 | "@vitejs/plugin-react": "^4.3.3", 30 | "autoprefixer": "^10.4.20", 31 | "electron": "^33.2.0", 32 | "electron-builder": "^24.13.3", 33 | "postcss": "^8.4.49", 34 | "postcss-import": "^16.1.0", 35 | "react": "^18.3.1", 36 | "react-dom": "^18.3.1", 37 | "tailwindcss": "^3.4.15", 38 | "typescript": "^5.4.2", 39 | "vite": "^5.4.11", 40 | "vite-plugin-electron": "^0.29.0", 41 | "vite-plugin-electron-renderer": "^0.14.6", 42 | "vitest": "^2.1.5" 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /postcss.config.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: { 3 | 'postcss-import': {}, 4 | 'tailwindcss/nesting': {}, 5 | tailwindcss: {}, 6 | autoprefixer: {}, 7 | }, 8 | } 9 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowman074/electron-vite-react/23537c8fed330749e0c7c625ee0273c82a4a7ed5/public/favicon.ico -------------------------------------------------------------------------------- /public/node.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | #root { 2 | max-width: 1280px; 3 | margin: 0 auto; 4 | padding: 2rem; 5 | text-align: center; 6 | } 7 | 8 | .logo-box { 9 | position: relative; 10 | height: 9em; 11 | } 12 | 13 | .logo { 14 | position: absolute; 15 | left: calc(50% - 4.5em); 16 | height: 6em; 17 | padding: 1.5em; 18 | will-change: filter; 19 | transition: filter 300ms; 20 | } 21 | .logo:hover { 22 | filter: drop-shadow(0 0 2em #646cffaa); 23 | } 24 | 25 | @keyframes logo-spin { 26 | from { 27 | transform: rotate(0deg); 28 | } 29 | to { 30 | transform: rotate(360deg); 31 | } 32 | } 33 | 34 | @media (prefers-reduced-motion: no-preference) { 35 | .logo.electron { 36 | animation: logo-spin infinite 20s linear; 37 | } 38 | } 39 | 40 | .card { 41 | padding: 2em; 42 | } 43 | 44 | .read-the-docs { 45 | color: #888; 46 | } 47 | 48 | .flex-center { 49 | display: flex; 50 | align-items: center; 51 | justify-content: center; 52 | } 53 | -------------------------------------------------------------------------------- /src/App.tsx: -------------------------------------------------------------------------------- 1 | import { useState } from 'react' 2 | import UpdateElectron from '@/components/update' 3 | import logoVite from './assets/logo-vite.svg' 4 | import logoElectron from './assets/logo-electron.svg' 5 | import './App.css' 6 | 7 | function App() { 8 | const [count, setCount] = useState(0) 9 | return ( 10 |
11 | 17 |

Electron + Vite + React

18 |
19 | 22 |

23 | Edit src/App.tsx and save to test HMR 24 |

25 |
26 |

27 | Click on the Electron + Vite logo to learn more 28 |

29 |
30 | Place static files into the/public folder Node logo 31 |
32 | 33 | 34 |
35 | ) 36 | } 37 | 38 | export default App -------------------------------------------------------------------------------- /src/assets/logo-electron.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/assets/logo-v1.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/assets/logo-vite.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/components/update/Modal/index.tsx: -------------------------------------------------------------------------------- 1 | import React, { ReactNode } from 'react' 2 | import { createPortal } from 'react-dom' 3 | import './modal.css' 4 | 5 | const ModalTemplate: React.FC void 11 | onOk?: () => void 12 | width?: number 13 | }>> = props => { 14 | const { 15 | title, 16 | children, 17 | footer, 18 | cancelText = 'Cancel', 19 | okText = 'OK', 20 | onCancel, 21 | onOk, 22 | width = 530, 23 | } = props 24 | 25 | return ( 26 |
27 |
28 |
29 |
30 |
31 |
{title}
32 | 36 | 40 | 41 | 42 | 43 | 44 |
45 |
{children}
46 | {typeof footer !== 'undefined' ? ( 47 |
48 | 49 | 50 |
51 | ) : footer} 52 |
53 |
54 |
55 | ) 56 | } 57 | 58 | const Modal = (props: Parameters[0] & { open: boolean }) => { 59 | const { open, ...omit } = props 60 | 61 | return createPortal( 62 | open ? ModalTemplate(omit) : null, 63 | document.body, 64 | ) 65 | } 66 | 67 | export default Modal 68 | -------------------------------------------------------------------------------- /src/components/update/Modal/modal.css: -------------------------------------------------------------------------------- 1 | .update-modal { 2 | --primary-color: rgb(224, 30, 90); 3 | 4 | .update-modal__mask { 5 | width: 100vw; 6 | height: 100vh; 7 | position: fixed; 8 | left: 0; 9 | top: 0; 10 | z-index: 9; 11 | background: rgba(0, 0, 0, 0.45); 12 | } 13 | 14 | .update-modal__warp { 15 | position: fixed; 16 | top: 50%; 17 | left: 50%; 18 | transform: translate(-50%, -50%); 19 | z-index: 19; 20 | } 21 | 22 | .update-modal__content { 23 | box-shadow: 0 0 10px -4px rgb(130, 86, 208); 24 | overflow: hidden; 25 | border-radius: 4px; 26 | 27 | .content__header { 28 | display: flex; 29 | line-height: 38px; 30 | background-color: var(--primary-color); 31 | 32 | .content__header-text { 33 | font-weight: bold; 34 | width: 0; 35 | flex-grow: 1; 36 | } 37 | } 38 | 39 | .update-modal--close { 40 | width: 30px; 41 | height: 30px; 42 | margin: 4px; 43 | line-height: 34px; 44 | text-align: center; 45 | cursor: pointer; 46 | 47 | svg { 48 | width: 17px; 49 | height: 17px; 50 | } 51 | } 52 | 53 | .content__body { 54 | padding: 10px; 55 | background-color: #fff; 56 | color: #333; 57 | } 58 | 59 | .content__footer { 60 | padding: 10px; 61 | background-color: #fff; 62 | display: flex; 63 | justify-content: flex-end; 64 | 65 | button { 66 | padding: 7px 11px; 67 | background-color: var(--primary-color); 68 | font-size: 14px; 69 | margin-left: 10px; 70 | 71 | &:first-child { 72 | margin-left: 0; 73 | } 74 | } 75 | } 76 | } 77 | 78 | .icon { 79 | padding: 0 15px; 80 | width: 20px; 81 | fill: currentColor; 82 | 83 | &:hover { 84 | color: rgba(0, 0, 0, 0.4); 85 | } 86 | } 87 | } -------------------------------------------------------------------------------- /src/components/update/Progress/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import './progress.css' 3 | 4 | const Progress: React.FC> = props => { 7 | const { percent = 0 } = props 8 | 9 | return ( 10 |
11 |
12 |
16 |
17 | {(percent ?? 0).toString().substring(0, 4)}% 18 |
19 | ) 20 | } 21 | 22 | export default Progress 23 | -------------------------------------------------------------------------------- /src/components/update/Progress/progress.css: -------------------------------------------------------------------------------- 1 | .update-progress { 2 | display: flex; 3 | align-items: center; 4 | 5 | .update-progress-pr { 6 | border: 1px solid #000; 7 | border-radius: 3px; 8 | height: 6px; 9 | width: 300px; 10 | } 11 | 12 | .update-progress-rate { 13 | height: 6px; 14 | border-radius: 3px; 15 | background-image: linear-gradient(to right, rgb(130, 86, 208) 0%, var(--primary-color) 100%) 16 | } 17 | 18 | .update-progress-num { 19 | margin: 0 10px; 20 | } 21 | } -------------------------------------------------------------------------------- /src/components/update/README.md: -------------------------------------------------------------------------------- 1 | # electron-updater 2 | 3 | English | [简体中文](README.zh-CN.md) 4 | 5 | > Use `electron-updater` to realize the update detection, download and installation of the electric program. 6 | 7 | ```sh 8 | npm i electron-updater 9 | ``` 10 | 11 | ### Main logic 12 | 13 | 1. ##### Configuration of the update the service address and update information script: 14 | 15 | Add a `publish` field to `electron-builder.json5` for configuring the update address and which strategy to use as the update service. 16 | 17 | ``` json5 18 | { 19 | "publish": { 20 | "provider": "generic", 21 | "channel": "latest", 22 | "url": "https://foo.com/" 23 | } 24 | } 25 | ``` 26 | 27 | For more information, please refer to : [electron-builder.json5...](https://github.com/electron-vite/electron-vite-react/blob/2f2880a9f19de50ff14a0785b32a4d5427477e55/electron-builder.json5#L38) 28 | 29 | 2. ##### The update logic of Electron: 30 | 31 | - Checking if an update is available; 32 | - Checking the version of the software on the server; 33 | - Checking if an update is available; 34 | - Downloading the new version of the software from the server (when an update is available); 35 | - Installation method; 36 | 37 | For more information, please refer to : [update...](https://github.com/electron-vite/electron-vite-react/blob/main/electron/main/update.ts) 38 | 39 | 3. ##### Updating UI pages in Electron: 40 | 41 | The main function is to provide a UI page for users to trigger the update logic mentioned in (2.) above. Users can click on the page to trigger different update functions in Electron. 42 | 43 | For more information, please refer to : [components/update...](https://github.com/electron-vite/electron-vite-react/blob/main/src/components/update/index.tsx) 44 | 45 | --- 46 | 47 | Here it is recommended to trigger updates through user actions (in this project, Electron update function is triggered after the user clicks on the "Check for updates" button). 48 | 49 | For more information on using `electron-updater` for Electron updates, please refer to the documentation : [auto-update](https://www.electron.build/.html) 50 | -------------------------------------------------------------------------------- /src/components/update/README.zh-CN.md: -------------------------------------------------------------------------------- 1 | # electron-auto-update 2 | 3 | [English](README.md) | 简体中文 4 | 5 | 使用`electron-updater`实现electron程序的更新检测、下载和安装等功能。 6 | 7 | ```sh 8 | npm i electron-updater 9 | ``` 10 | 11 | ### 主要逻辑 12 | 13 | 1. ##### 更新地址、更新信息脚本的配置 14 | 15 | 在`electron-builder.json5`添加`publish`字段,用来配置更新地址和使用哪种策略作为更新服务 16 | 17 | ``` json5 18 | { 19 | "publish": { 20 | "provider": "generic", // 提供者、提供商 21 | "channel": "latest", // 生成yml文件的名称 22 | "url": "https://foo.com/" //更新地址 23 | } 24 | } 25 | ``` 26 | 27 | 更多见 : [electron-builder.json5...](xxx) 28 | 29 | 2. ##### Electron更新逻辑 30 | 31 | - 检测更新是否可用; 32 | 33 | - 检测服务端的软件版本; 34 | 35 | - 检测更新是否可用; 36 | 37 | - 下载服务端新版软件(当更新可用); 38 | - 安装方式; 39 | 40 | 更多见 : [update...](https://github.com/electron-vite/electron-vite-react/blob/main/electron/main/update.ts) 41 | 42 | 3. ##### Electron更新UI页面 43 | 44 | 主要功能是:用户触发上述(2.)更新逻辑的UI页面。用户可以通过点击页面触发electron更新的不同功能。 45 | 更多见 : [components/update.ts...](https://github.com/electron-vite/electron-vite-react/tree/main/src/components/update/index.tsx) 46 | 47 | --- 48 | 49 | 这里建议更新触发以用户操作触发(本项目的以用户点击 **更新检测** 后触发electron更新功能) 50 | 51 | 关于更多使用`electron-updater`进行electron更新,见文档:[auto-update](https://www.electron.build/.html) 52 | -------------------------------------------------------------------------------- /src/components/update/index.tsx: -------------------------------------------------------------------------------- 1 | import type { ProgressInfo } from 'electron-updater' 2 | import { useCallback, useEffect, useState } from 'react' 3 | import Modal from '@/components/update/Modal' 4 | import Progress from '@/components/update/Progress' 5 | import './update.css' 6 | 7 | const Update = () => { 8 | const [checking, setChecking] = useState(false) 9 | const [updateAvailable, setUpdateAvailable] = useState(false) 10 | const [versionInfo, setVersionInfo] = useState() 11 | const [updateError, setUpdateError] = useState() 12 | const [progressInfo, setProgressInfo] = useState>() 13 | const [modalOpen, setModalOpen] = useState(false) 14 | const [modalBtn, setModalBtn] = useState<{ 15 | cancelText?: string 16 | okText?: string 17 | onCancel?: () => void 18 | onOk?: () => void 19 | }>({ 20 | onCancel: () => setModalOpen(false), 21 | onOk: () => window.ipcRenderer.invoke('start-download'), 22 | }) 23 | 24 | const checkUpdate = async () => { 25 | setChecking(true) 26 | /** 27 | * @type {import('electron-updater').UpdateCheckResult | null | { message: string, error: Error }} 28 | */ 29 | const result = await window.ipcRenderer.invoke('check-update') 30 | setProgressInfo({ percent: 0 }) 31 | setChecking(false) 32 | setModalOpen(true) 33 | if (result?.error) { 34 | setUpdateAvailable(false) 35 | setUpdateError(result?.error) 36 | } 37 | } 38 | 39 | const onUpdateCanAvailable = useCallback((_event: Electron.IpcRendererEvent, arg1: VersionInfo) => { 40 | setVersionInfo(arg1) 41 | setUpdateError(undefined) 42 | // Can be update 43 | if (arg1.update) { 44 | setModalBtn(state => ({ 45 | ...state, 46 | cancelText: 'Cancel', 47 | okText: 'Update', 48 | onOk: () => window.ipcRenderer.invoke('start-download'), 49 | })) 50 | setUpdateAvailable(true) 51 | } else { 52 | setUpdateAvailable(false) 53 | } 54 | }, []) 55 | 56 | const onUpdateError = useCallback((_event: Electron.IpcRendererEvent, arg1: ErrorType) => { 57 | setUpdateAvailable(false) 58 | setUpdateError(arg1) 59 | }, []) 60 | 61 | const onDownloadProgress = useCallback((_event: Electron.IpcRendererEvent, arg1: ProgressInfo) => { 62 | setProgressInfo(arg1) 63 | }, []) 64 | 65 | const onUpdateDownloaded = useCallback((_event: Electron.IpcRendererEvent, ...args: any[]) => { 66 | setProgressInfo({ percent: 100 }) 67 | setModalBtn(state => ({ 68 | ...state, 69 | cancelText: 'Later', 70 | okText: 'Install now', 71 | onOk: () => window.ipcRenderer.invoke('quit-and-install'), 72 | })) 73 | }, []) 74 | 75 | useEffect(() => { 76 | // Get version information and whether to update 77 | window.ipcRenderer.on('update-can-available', onUpdateCanAvailable) 78 | window.ipcRenderer.on('update-error', onUpdateError) 79 | window.ipcRenderer.on('download-progress', onDownloadProgress) 80 | window.ipcRenderer.on('update-downloaded', onUpdateDownloaded) 81 | 82 | return () => { 83 | window.ipcRenderer.off('update-can-available', onUpdateCanAvailable) 84 | window.ipcRenderer.off('update-error', onUpdateError) 85 | window.ipcRenderer.off('download-progress', onDownloadProgress) 86 | window.ipcRenderer.off('update-downloaded', onUpdateDownloaded) 87 | } 88 | }, []) 89 | 90 | return ( 91 | <> 92 | 100 |
101 | {updateError 102 | ? ( 103 |
104 |

Error downloading the latest version.

105 |

{updateError.message}

106 |
107 | ) : updateAvailable 108 | ? ( 109 |
110 |
The last version is: v{versionInfo?.newVersion}
111 |
v{versionInfo?.version} -> v{versionInfo?.newVersion}
112 |
113 |
Update progress:
114 |
115 | 116 |
117 |
118 |
119 | ) 120 | : ( 121 |
{JSON.stringify(versionInfo ?? {}, null, 2)}
122 | )} 123 |
124 |
125 | 128 | 129 | ) 130 | } 131 | 132 | export default Update 133 | -------------------------------------------------------------------------------- /src/components/update/update.css: -------------------------------------------------------------------------------- 1 | .modal-slot { 2 | .update-progress { 3 | display: flex; 4 | } 5 | 6 | .new-version__target, 7 | .update__progress { 8 | margin-left: 40px; 9 | } 10 | 11 | .progress__title { 12 | margin-right: 10px; 13 | } 14 | 15 | .progress__bar { 16 | width: 0; 17 | flex-grow: 1; 18 | } 19 | 20 | .can-not-available { 21 | padding: 20px; 22 | text-align: center; 23 | } 24 | } -------------------------------------------------------------------------------- /src/demos/ipc.ts: -------------------------------------------------------------------------------- 1 | 2 | window.ipcRenderer.on('main-process-message', (_event, ...args) => { 3 | console.log('[Receive Main-process message]:', ...args) 4 | }) 5 | -------------------------------------------------------------------------------- /src/demos/node.ts: -------------------------------------------------------------------------------- 1 | import { lstat } from 'node:fs/promises' 2 | import { cwd } from 'node:process' 3 | 4 | lstat(cwd()).then(stats => { 5 | console.log('[fs.lstat]', stats) 6 | }).catch(err => { 7 | console.error(err) 8 | }) 9 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | 5 | :root { 6 | font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; 7 | line-height: 1.5; 8 | font-weight: 400; 9 | 10 | color-scheme: light dark; 11 | color: rgba(255, 255, 255, 0.87); 12 | background-color: #242424; 13 | 14 | font-synthesis: none; 15 | text-rendering: optimizeLegibility; 16 | -webkit-font-smoothing: antialiased; 17 | -moz-osx-font-smoothing: grayscale; 18 | -webkit-text-size-adjust: 100%; 19 | } 20 | 21 | a { 22 | font-weight: 500; 23 | color: #646cff; 24 | text-decoration: inherit; 25 | } 26 | a:hover { 27 | color: #535bf2; 28 | } 29 | 30 | body { 31 | margin: 0; 32 | display: flex; 33 | place-items: center; 34 | min-width: 320px; 35 | min-height: 100vh; 36 | } 37 | 38 | h1 { 39 | font-size: 3.2em; 40 | line-height: 1.1; 41 | } 42 | 43 | button { 44 | border-radius: 8px; 45 | border: 1px solid transparent; 46 | padding: 0.6em 1.2em; 47 | font-size: 1em; 48 | font-weight: 500; 49 | font-family: inherit; 50 | background-color: #1a1a1a; 51 | cursor: pointer; 52 | transition: border-color 0.25s; 53 | } 54 | button:hover { 55 | border-color: #646cff; 56 | } 57 | button:focus, 58 | button:focus-visible { 59 | outline: 4px auto -webkit-focus-ring-color; 60 | } 61 | 62 | code { 63 | background-color: #1a1a1a; 64 | padding: 2px 4px; 65 | margin: 0 4px; 66 | border-radius: 4px; 67 | } 68 | 69 | .card { 70 | padding: 2em; 71 | } 72 | 73 | #app { 74 | max-width: 1280px; 75 | margin: 0 auto; 76 | padding: 2rem; 77 | text-align: center; 78 | } 79 | 80 | @media (prefers-color-scheme: light) { 81 | :root { 82 | color: #213547; 83 | background-color: #ffffff; 84 | } 85 | a:hover { 86 | color: #747bff; 87 | } 88 | button { 89 | background-color: #f9f9f9; 90 | } 91 | code { 92 | background-color: #f9f9f9; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import ReactDOM from 'react-dom/client' 3 | import App from './App' 4 | 5 | import './index.css' 6 | 7 | import './demos/ipc' 8 | // If you want use Node.js, the`nodeIntegration` needs to be enabled in the Main process. 9 | // import './demos/node' 10 | 11 | ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render( 12 | 13 | 14 | , 15 | ) 16 | 17 | postMessage({ payload: 'removeLoading' }, '*') 18 | -------------------------------------------------------------------------------- /src/type/electron-updater.d.ts: -------------------------------------------------------------------------------- 1 | interface VersionInfo { 2 | update: boolean 3 | version: string 4 | newVersion?: string 5 | } 6 | 7 | interface ErrorType { 8 | message: string 9 | error: Error 10 | } 11 | -------------------------------------------------------------------------------- /src/vite-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | interface Window { 4 | // expose in the `electron/preload/index.ts` 5 | ipcRenderer: import('electron').IpcRenderer 6 | } 7 | -------------------------------------------------------------------------------- /tailwind.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('tailwindcss').Config} */ 2 | export default { 3 | content: [ 4 | './index.html', 5 | './src/**/*.{js,ts,jsx,tsx}', 6 | ], 7 | theme: { 8 | extend: {}, 9 | }, 10 | corePlugins: { 11 | preflight: false, 12 | }, 13 | plugins: [], 14 | } 15 | -------------------------------------------------------------------------------- /test/e2e.spec.ts: -------------------------------------------------------------------------------- 1 | import path from 'node:path' 2 | import { 3 | type ElectronApplication, 4 | type Page, 5 | type JSHandle, 6 | _electron as electron, 7 | } from 'playwright' 8 | import type { BrowserWindow } from 'electron' 9 | import { 10 | beforeAll, 11 | afterAll, 12 | describe, 13 | expect, 14 | test, 15 | } from 'vitest' 16 | 17 | const root = path.join(__dirname, '..') 18 | let electronApp: ElectronApplication 19 | let page: Page 20 | 21 | if (process.platform === 'linux') { 22 | // pass ubuntu 23 | test(() => expect(true).true) 24 | } else { 25 | beforeAll(async () => { 26 | electronApp = await electron.launch({ 27 | args: ['.', '--no-sandbox'], 28 | cwd: root, 29 | env: { ...process.env, NODE_ENV: 'development' }, 30 | }) 31 | page = await electronApp.firstWindow() 32 | 33 | const mainWin: JSHandle = await electronApp.browserWindow(page) 34 | await mainWin.evaluate(async (win) => { 35 | win.webContents.executeJavaScript('console.log("Execute JavaScript with e2e testing.")') 36 | }) 37 | }) 38 | 39 | afterAll(async () => { 40 | await page.screenshot({ path: 'test/screenshots/e2e.png' }) 41 | await page.close() 42 | await electronApp.close() 43 | }) 44 | 45 | describe('[electron-vite-react] e2e tests', async () => { 46 | test('startup', async () => { 47 | const title = await page.title() 48 | expect(title).eq('Electron + Vite + React') 49 | }) 50 | 51 | test('should be home page is load correctly', async () => { 52 | const h1 = await page.$('h1') 53 | const title = await h1?.textContent() 54 | expect(title).eq('Electron + Vite + React') 55 | }) 56 | 57 | test('should be count button can click', async () => { 58 | const countButton = await page.$('button') 59 | await countButton?.click() 60 | const countValue = await countButton?.textContent() 61 | expect(countValue).eq('count is 1') 62 | }) 63 | }) 64 | } 65 | -------------------------------------------------------------------------------- /test/screenshots/e2e.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/snowman074/electron-vite-react/23537c8fed330749e0c7c625ee0273c82a4a7ed5/test/screenshots/e2e.png -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ESNext", 4 | "useDefineForClassFields": true, 5 | "lib": ["DOM", "DOM.Iterable", "ESNext"], 6 | "allowJs": false, 7 | "skipLibCheck": true, 8 | "esModuleInterop": false, 9 | "allowSyntheticDefaultImports": true, 10 | "strict": true, 11 | "forceConsistentCasingInFileNames": true, 12 | "module": "ESNext", 13 | "moduleResolution": "Node", 14 | "resolveJsonModule": true, 15 | "isolatedModules": true, 16 | "noEmit": true, 17 | "jsx": "react-jsx", 18 | "baseUrl": "./", 19 | "paths": { 20 | "@/*": [ 21 | "src/*" 22 | ] 23 | }, 24 | }, 25 | "include": ["src", "electron"], 26 | "references": [{ "path": "./tsconfig.node.json" }] 27 | } 28 | -------------------------------------------------------------------------------- /tsconfig.node.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "composite": true, 4 | "module": "ESNext", 5 | "moduleResolution": "Node", 6 | "resolveJsonModule": true, 7 | "allowSyntheticDefaultImports": true 8 | }, 9 | "include": ["vite.config.ts", "package.json"] 10 | } 11 | -------------------------------------------------------------------------------- /vite.config.ts: -------------------------------------------------------------------------------- 1 | import { rmSync } from 'node:fs' 2 | import path from 'node:path' 3 | import { defineConfig } from 'vite' 4 | import react from '@vitejs/plugin-react' 5 | import electron from 'vite-plugin-electron/simple' 6 | import pkg from './package.json' 7 | 8 | // https://vitejs.dev/config/ 9 | export default defineConfig(({ command }) => { 10 | rmSync('dist-electron', { recursive: true, force: true }) 11 | 12 | const isServe = command === 'serve' 13 | const isBuild = command === 'build' 14 | const sourcemap = isServe || !!process.env.VSCODE_DEBUG 15 | 16 | return { 17 | resolve: { 18 | alias: { 19 | '@': path.join(__dirname, 'src') 20 | }, 21 | }, 22 | plugins: [ 23 | react(), 24 | electron({ 25 | main: { 26 | // Shortcut of `build.lib.entry` 27 | entry: 'electron/main/index.ts', 28 | onstart(args) { 29 | if (process.env.VSCODE_DEBUG) { 30 | console.log(/* For `.vscode/.debug.script.mjs` */'[startup] Electron App') 31 | } else { 32 | args.startup() 33 | } 34 | }, 35 | vite: { 36 | build: { 37 | sourcemap, 38 | minify: isBuild, 39 | outDir: 'dist-electron/main', 40 | rollupOptions: { 41 | external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}), 42 | }, 43 | }, 44 | }, 45 | }, 46 | preload: { 47 | // Shortcut of `build.rollupOptions.input`. 48 | // Preload scripts may contain Web assets, so use the `build.rollupOptions.input` instead `build.lib.entry`. 49 | input: 'electron/preload/index.ts', 50 | vite: { 51 | build: { 52 | sourcemap: sourcemap ? 'inline' : undefined, // #332 53 | minify: isBuild, 54 | outDir: 'dist-electron/preload', 55 | rollupOptions: { 56 | external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}), 57 | }, 58 | }, 59 | }, 60 | }, 61 | // Ployfill the Electron and Node.js API for Renderer process. 62 | // If you want use Node.js in Renderer process, the `nodeIntegration` needs to be enabled in the Main process. 63 | // See 👉 https://github.com/electron-vite/vite-plugin-electron-renderer 64 | renderer: {}, 65 | }), 66 | ], 67 | server: process.env.VSCODE_DEBUG && (() => { 68 | const url = new URL(pkg.debug.env.VITE_DEV_SERVER_URL) 69 | return { 70 | host: url.hostname, 71 | port: +url.port, 72 | } 73 | })(), 74 | clearScreen: false, 75 | } 76 | }) 77 | -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vitest/config' 2 | 3 | export default defineConfig({ 4 | test: { 5 | root: __dirname, 6 | include: ['test/**/*.{test,spec}.?(c|m)[jt]s?(x)'], 7 | testTimeout: 1000 * 29, 8 | }, 9 | }) 10 | --------------------------------------------------------------------------------