6 Commits

Author SHA1 Message Date
草鞋没号
19995fcc1f chore: update comments 2024-01-03 16:09:47 +08:00
草鞋没号
3bdccd268c feat: use ipcRenderer demo 2024-01-03 16:01:59 +08:00
草鞋没号
7ec046370f refactor: use vite-plugin-electron/simple API 2024-01-02 12:17:48 +08:00
草鞋没号
374596c331 chore: bump vite-plugin-electron to 0.28.0-beta.2 2024-01-02 11:46:21 +08:00
草鞋没号
0d71c4bcd1 feat: electron@28, supports "type": "module" 2023-12-30 14:14:46 +08:00
草鞋没号
7ec78d0366 chore: bump deps 2023-12-30 14:12:23 +08:00
9 changed files with 152 additions and 48 deletions

View File

@@ -1,6 +1,10 @@
import { app, BrowserWindow, shell, ipcMain } from 'electron'
import { release } from 'node:os'
import { join } from 'node:path'
import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
// The built directory structure
//
@@ -8,7 +12,7 @@ import { join } from 'node:path'
// │ ├─┬ main
// │ │ └── index.js > Electron-Main
// │ └─┬ preload
// │ └── index.js > Preload-Scripts
// │ └── index.mjs > Preload-Scripts
// ├─┬ dist
// │ └── index.html > Electron-Renderer
//
@@ -36,7 +40,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')
@@ -47,10 +51,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,
},
})

View File

@@ -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<string, any>) {
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)) {

View File

@@ -1,6 +1,6 @@
{
"name": "electron-vue-vite",
"version": "2.0.0",
"version": "28.0.0",
"main": "dist-electron/main/index.js",
"description": "Really simple Electron + Vue + Vite boilerplate.",
"author": "草鞋没号 <308487730@qq.com>",
@@ -18,21 +18,22 @@
"VITE_DEV_SERVER_URL": "http://127.0.0.1:3344/"
}
},
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build && electron-builder",
"preview": "vite preview"
},
"devDependencies": {
"@vitejs/plugin-vue": "^4.3.3",
"electron": "^27.1.3",
"electron-builder": "^24.6.3",
"@vitejs/plugin-vue": "^5.0.1",
"electron": "^28.1.0",
"electron-builder": "^24.9.1",
"tree-kill": "^1.2.2",
"typescript": "^5.1.6",
"vite": "^5.0.4",
"vite-plugin-electron": "^0.15.5",
"typescript": "^5.3.3",
"vite": "^5.0.10",
"vite-plugin-electron": "^0.28.0-beta.2",
"vite-plugin-electron-renderer": "^0.14.5",
"vue": "^3.3.4",
"vue-tsc": "^1.8.8"
"vue": "^3.4.1",
"vue-tsc": "^1.8.27"
}
}

4
src/demos/ipc.ts Normal file
View File

@@ -0,0 +1,4 @@
window.ipcRenderer.on('main-process-message', (_event, ...args) => {
console.log('[Receive Main-process message]:', ...args)
})

View File

@@ -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)

View File

@@ -1,7 +1,11 @@
import { createApp } from 'vue'
import "./style.css"
import App from './App.vue'
import './samples/node-api'
import './style.css'
import './demos/ipc'
// If you want use Node.js, the`nodeIntegration` needs to be enabled in the Main process.
// import './demos/node'
createApp(App)
.mount('#app')

5
src/vite-env.d.ts vendored
View File

@@ -5,3 +5,8 @@ declare module '*.vue' {
const component: DefineComponent<{}, {}, any>
export default component
}
interface Window {
// expose in the `electron/preload/index.ts`
ipcRenderer: import('electron').IpcRenderer
}

76
vite.config.flat.txt Normal file
View File

@@ -0,0 +1,76 @@
import { rmSync } from 'node:fs'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
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 {
plugins: [
vue(),
electron([
{
// Main process entry file of the Electron App.
entry: 'electron/main/index.ts',
onstart({ startup }) {
if (process.env.VSCODE_DEBUG) {
console.log(/* For `.vscode/.debug.script.mjs` */'[startup] Electron App')
} else {
startup()
}
},
vite: {
build: {
sourcemap,
minify: isBuild,
outDir: 'dist-electron/main',
rollupOptions: {
// Some third-party Node.js libraries may not be built correctly by Vite, especially `C/C++` addons,
// we can use `external` to exclude them to ensure they work correctly.
// Others need to put them in `dependencies` to ensure they are collected into `app.asar` after the app is built.
// Of course, this is not absolute, just this way is relatively simple. :)
external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}),
},
},
},
},
{
entry: 'electron/preload/index.ts',
onstart({ reload }) {
// Notify the Renderer process to reload the page when the Preload scripts build is complete,
// instead of restarting the entire Electron App.
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,
}
})

View File

@@ -1,14 +1,12 @@
import { rmSync } from 'node:fs'
import fs from 'node:fs'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import electron from 'vite-plugin-electron'
import renderer from 'vite-plugin-electron-renderer'
import { notBundle } from 'vite-plugin-electron/plugin'
import electron from 'vite-plugin-electron/simple'
import pkg from './package.json'
// https://vitejs.dev/config/
export default defineConfig(({ command }) => {
rmSync('dist-electron', { recursive: true, force: true })
fs.rmSync('dist-electron', { recursive: true, force: true })
const isServe = command === 'serve'
const isBuild = command === 'build'
@@ -17,9 +15,9 @@ export default defineConfig(({ command }) => {
return {
plugins: [
vue(),
electron([
{
// Main process entry file of the Electron App.
electron({
main: {
// Shortcut of `build.lib.entry`
entry: 'electron/main/index.ts',
onstart({ startup }) {
if (process.env.VSCODE_DEBUG) {
@@ -41,20 +39,12 @@ export default defineConfig(({ command }) => {
external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}),
},
},
plugins: [
// This is just an option to improve build performance, it's non-deterministic!
// e.g. `import log from 'electron-log'` -> `const log = require('electron-log')`
isServe && notBundle(),
],
},
},
{
entry: 'electron/preload/index.ts',
onstart({ reload }) {
// Notify the Renderer process to reload the page when the Preload scripts build is complete,
// instead of restarting the entire Electron App.
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
@@ -64,14 +54,13 @@ export default defineConfig(({ command }) => {
external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}),
},
},
plugins: [
isServe && notBundle(),
],
},
}
]),
// Use Node.js API in the Renderer process
renderer(),
},
// Ployfill the Electron and Node.js API for Renderer process.
// If you want use Node.js in Renderer process, the `nodeIntegration` needs to be enabled in the Main process.
// See 👉 https://github.com/electron-vite/vite-plugin-electron-renderer
renderer: {},
}),
],
server: process.env.VSCODE_DEBUG && (() => {
const url = new URL(pkg.debug.env.VITE_DEV_SERVER_URL)