diff --git a/electron/main/index.ts b/electron/main/index.ts index 9eb5399..2c282d2 100644 --- a/electron/main/index.ts +++ b/electron/main/index.ts @@ -1,15 +1,19 @@ import { app, BrowserWindow, shell, ipcMain } from 'electron' import { release } from 'node:os' -import { join } from 'node:path' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' import { update } from './update' +const __filename = fileURLToPath(import.meta.url) +const __dirname = dirname(__filename) + // The built directory structure // // ├─┬ dist-electron // │ ├─┬ main // │ │ └── index.js > Electron-Main // │ └─┬ preload -// │ └── index.js > Preload-Scripts +// │ └── index.mjs > Preload-Scripts // ├─┬ dist // │ └── index.html > Electron-Renderer // @@ -37,7 +41,7 @@ if (!app.requestSingleInstanceLock()) { let win: BrowserWindow | null = null // Here, you can also use other preload -const preload = join(__dirname, '../preload/index.js') +const preload = join(__dirname, '../preload/index.mjs') const url = process.env.VITE_DEV_SERVER_URL const indexHtml = join(process.env.DIST, 'index.html') @@ -48,10 +52,11 @@ async function createWindow() { webPreferences: { preload, // Warning: Enable nodeIntegration and disable contextIsolation is not secure in production + // nodeIntegration: true, + // Consider using contextBridge.exposeInMainWorld // Read more on https://www.electronjs.org/docs/latest/tutorial/context-isolation - nodeIntegration: true, - contextIsolation: false, + // contextIsolation: false, }, }) diff --git a/electron/main/update.ts b/electron/main/update.ts index db946a4..a973b3e 100644 --- a/electron/main/update.ts +++ b/electron/main/update.ts @@ -1,10 +1,12 @@ import { app, ipcMain } from 'electron' -import { - type ProgressInfo, - type UpdateDownloadedEvent, - autoUpdater +import { createRequire } from 'node:module' +import type { + ProgressInfo, + UpdateDownloadedEvent, } from 'electron-updater' +const { autoUpdater } = createRequire(import.meta.url)('electron-updater'); + export function update(win: Electron.BrowserWindow) { // When set to false, the update download will be triggered through the API diff --git a/electron/preload/index.ts b/electron/preload/index.ts index 0f6fb04..bcfd20e 100644 --- a/electron/preload/index.ts +++ b/electron/preload/index.ts @@ -1,3 +1,28 @@ +import { ipcRenderer, contextBridge } from 'electron' + +// --------- Expose some API to the Renderer process --------- +contextBridge.exposeInMainWorld('ipcRenderer', withPrototype(ipcRenderer)) + +// `exposeInMainWorld` can't detect attributes and methods of `prototype`, manually patching it. +function withPrototype(obj: Record) { + const protos = Object.getPrototypeOf(obj) + + for (const [key, value] of Object.entries(protos)) { + if (Object.prototype.hasOwnProperty.call(obj, key)) continue + + if (typeof value === 'function') { + // Some native APIs, like `NodeJS.EventEmitter['on']`, don't work in the Renderer process. Wrapping them into a function. + obj[key] = function (...args: any) { + return value.call(obj, ...args) + } + } else { + obj[key] = value + } + } + return obj +} + +// --------- Preload scripts loading --------- function domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) { return new Promise(resolve => { if (condition.includes(document.readyState)) { diff --git a/package.json b/package.json index bd6a8d0..dd7f471 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "VITE_DEV_SERVER_URL": "http://127.0.0.1:7777/" } }, + "type": "module", "scripts": { "dev": "vite", "build": "tsc && vite build && electron-builder", @@ -27,18 +28,15 @@ "@types/react-dom": "^18.2.7", "@vitejs/plugin-react": "^4.0.4", "autoprefixer": "^10.4.16", - "electron": "^26.0.0", + "electron": "^28.1.0", "electron-builder": "^24.6.3", "postcss": "^8.4.31", "react": "^18.2.0", "react-dom": "^18.2.0", "tailwindcss": "^3.3.3", "typescript": "^5.1.6", - "vite": "^4.4.9", - "vite-plugin-electron": "^0.15.5", + "vite": "^5.0.10", + "vite-plugin-electron": "^0.28.0-beta.2", "vite-plugin-electron-renderer": "^0.14.5" - }, - "engines": { - "node": "^14.18.0 || >=16.0.0" } } diff --git a/src/App.tsx b/src/App.tsx index 73cb692..c5462d1 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -4,8 +4,6 @@ import logoVite from './assets/logo-vite.svg' import logoElectron from './assets/logo-electron.svg' import './App.css' -console.log('[App.tsx]', `Hello world from Electron ${process.versions.electron}!`) - function App() { const [count, setCount] = useState(0) return ( diff --git a/src/components/update/index.tsx b/src/components/update/index.tsx index 9e28bb0..2f73940 100644 --- a/src/components/update/index.tsx +++ b/src/components/update/index.tsx @@ -1,4 +1,3 @@ -import { ipcRenderer } from 'electron' import type { ProgressInfo } from 'electron-updater' import { useCallback, useEffect, useState } from 'react' import Modal from '@/components/update/Modal' @@ -19,7 +18,7 @@ const Update = () => { onOk?: () => void }>({ onCancel: () => setModalOpen(false), - onOk: () => ipcRenderer.invoke('start-download'), + onOk: () => window.ipcRenderer.invoke('start-download'), }) const checkUpdate = async () => { @@ -27,7 +26,7 @@ const Update = () => { /** * @type {import('electron-updater').UpdateCheckResult | null | { message: string, error: Error }} */ - const result = await ipcRenderer.invoke('check-update') + const result = await window.ipcRenderer.invoke('check-update') setProgressInfo({ percent: 0 }) setChecking(false) setModalOpen(true) @@ -46,7 +45,7 @@ const Update = () => { ...state, cancelText: 'Cancel', okText: 'Update', - onOk: () => ipcRenderer.invoke('start-download'), + onOk: () => window.ipcRenderer.invoke('start-download'), })) setUpdateAvailable(true) } else { @@ -69,22 +68,22 @@ const Update = () => { ...state, cancelText: 'Later', okText: 'Install now', - onOk: () => ipcRenderer.invoke('quit-and-install'), + onOk: () => window.ipcRenderer.invoke('quit-and-install'), })) }, []) useEffect(() => { // Get version information and whether to update - ipcRenderer.on('update-can-available', onUpdateCanAvailable) - ipcRenderer.on('update-error', onUpdateError) - ipcRenderer.on('download-progress', onDownloadProgress) - ipcRenderer.on('update-downloaded', onUpdateDownloaded) + window.ipcRenderer.on('update-can-available', onUpdateCanAvailable) + window.ipcRenderer.on('update-error', onUpdateError) + window.ipcRenderer.on('download-progress', onDownloadProgress) + window.ipcRenderer.on('update-downloaded', onUpdateDownloaded) return () => { - ipcRenderer.off('update-can-available', onUpdateCanAvailable) - ipcRenderer.off('update-error', onUpdateError) - ipcRenderer.off('download-progress', onDownloadProgress) - ipcRenderer.off('update-downloaded', onUpdateDownloaded) + window.ipcRenderer.off('update-can-available', onUpdateCanAvailable) + window.ipcRenderer.off('update-error', onUpdateError) + window.ipcRenderer.off('download-progress', onDownloadProgress) + window.ipcRenderer.off('update-downloaded', onUpdateDownloaded) } }, []) diff --git a/src/demos/ipc.ts b/src/demos/ipc.ts new file mode 100644 index 0000000..b94a939 --- /dev/null +++ b/src/demos/ipc.ts @@ -0,0 +1,5 @@ +import { ipcRenderer } from 'electron' + +ipcRenderer.on('main-process-message', (_event, ...args) => { + console.log('[Receive Main-process message]:', ...args) +}) diff --git a/src/samples/node-api.ts b/src/demos/node.ts similarity index 52% rename from src/samples/node-api.ts rename to src/demos/node.ts index f7a4d4d..277e6a3 100644 --- a/src/samples/node-api.ts +++ b/src/demos/node.ts @@ -1,10 +1,5 @@ import { lstat } from 'node:fs/promises' import { cwd } from 'node:process' -import { ipcRenderer } from 'electron' - -ipcRenderer.on('main-process-message', (_event, ...args) => { - console.log('[Receive Main-process message]:', ...args) -}) lstat(cwd()).then(stats => { console.log('[fs.lstat]', stats) diff --git a/src/main.tsx b/src/main.tsx index c4647c7..312b3b2 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -1,9 +1,13 @@ import React from 'react' import ReactDOM from 'react-dom/client' import App from './App' -import './samples/node-api' + import './index.css' +// `nodeIntegration` needs to be enabled in the Main process. +// import './demos/node' +// import './demos/ipc' + ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render( diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts index 11f02fe..53361d3 100644 --- a/src/vite-env.d.ts +++ b/src/vite-env.d.ts @@ -1 +1,6 @@ /// + +interface Window { + // expose in the `electron/preload/index.ts` + ipcRenderer: import('electron').IpcRenderer +} diff --git a/vite.config.flat.txt b/vite.config.flat.txt new file mode 100644 index 0000000..66b0dcd --- /dev/null +++ b/vite.config.flat.txt @@ -0,0 +1,78 @@ +import { rmSync } from 'node:fs' +import path from 'node:path' +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import electron from 'vite-plugin-electron' +import renderer from 'vite-plugin-electron-renderer' +import pkg from './package.json' + +// https://vitejs.dev/config/ +export default defineConfig(({ command }) => { + rmSync('dist-electron', { recursive: true, force: true }) + + const isServe = command === 'serve' + const isBuild = command === 'build' + const sourcemap = isServe || !!process.env.VSCODE_DEBUG + + return { + resolve: { + alias: { + '@': path.join(__dirname, 'src') + }, + }, + plugins: [ + react(), + electron([ + { + // Main-Process entry file of the Electron App. + entry: 'electron/main/index.ts', + onstart(options) { + if (process.env.VSCODE_DEBUG) { + console.log(/* For `.vscode/.debug.script.mjs` */'[startup] Electron App') + } else { + options.startup() + } + }, + vite: { + build: { + sourcemap, + minify: isBuild, + outDir: 'dist-electron/main', + rollupOptions: { + external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}), + }, + }, + }, + }, + { + entry: 'electron/preload/index.ts', + onstart(options) { + // Notify the Renderer-Process to reload the page when the Preload-Scripts build is complete, + // instead of restarting the entire Electron App. + options.reload() + }, + vite: { + build: { + sourcemap: sourcemap ? 'inline' : undefined, // #332 + minify: isBuild, + outDir: 'dist-electron/preload', + rollupOptions: { + external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}), + }, + }, + }, + } + ]), + // Use Node.js API in the Renderer-process + renderer(), + ], + server: process.env.VSCODE_DEBUG && (() => { + const url = new URL(pkg.debug.env.VITE_DEV_SERVER_URL) + return { + host: url.hostname, + port: +url.port, + } + })(), + clearScreen: false, + } +}) diff --git a/vite.config.ts b/vite.config.ts index 66b0dcd..c85c585 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -2,8 +2,7 @@ import { rmSync } from 'node:fs' import path from 'node:path' import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' -import electron from 'vite-plugin-electron' -import renderer from 'vite-plugin-electron-renderer' +import electron from 'vite-plugin-electron/simple' import pkg from './package.json' // https://vitejs.dev/config/ @@ -22,15 +21,15 @@ export default defineConfig(({ command }) => { }, plugins: [ react(), - electron([ - { - // Main-Process entry file of the Electron App. + electron({ + main: { + // Shortcut of `build.lib.entry` entry: 'electron/main/index.ts', - onstart(options) { + onstart(args) { if (process.env.VSCODE_DEBUG) { console.log(/* For `.vscode/.debug.script.mjs` */'[startup] Electron App') } else { - options.startup() + args.startup() } }, vite: { @@ -44,13 +43,10 @@ export default defineConfig(({ command }) => { }, }, }, - { - entry: 'electron/preload/index.ts', - onstart(options) { - // Notify the Renderer-Process to reload the page when the Preload-Scripts build is complete, - // instead of restarting the entire Electron App. - options.reload() - }, + preload: { + // Shortcut of `build.rollupOptions.input`. + // Preload scripts may contain Web assets, so use the `build.rollupOptions.input` instead `build.lib.entry`. + input: 'electron/preload/index.ts', vite: { build: { sourcemap: sourcemap ? 'inline' : undefined, // #332 @@ -61,10 +57,10 @@ export default defineConfig(({ command }) => { }, }, }, - } - ]), - // Use Node.js API in the Renderer-process - renderer(), + }, + // Use Node.js API in the Renderer process + renderer: {}, + }), ], server: process.env.VSCODE_DEBUG && (() => { const url = new URL(pkg.debug.env.VITE_DEV_SERVER_URL)