Merge pull request #13 from PAXANDDOS/comments

Comments and format
This commit is contained in:
草鞋没号 2022-02-07 09:44:07 +08:00 committed by GitHub
commit e4087edffe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 98 additions and 83 deletions

View File

@ -3,7 +3,10 @@ import { release } from 'os'
import { join } from 'path' import { join } from 'path'
import './samples/electron-store' import './samples/electron-store'
// Disable GPU Acceleration for Windows 7
if (release().startsWith('6.1')) app.disableHardwareAcceleration() if (release().startsWith('6.1')) app.disableHardwareAcceleration()
// Set application name for Windows 10+ notifications
if (process.platform === 'win32') app.setAppUserModelId(app.getName()) if (process.platform === 'win32') app.setAppUserModelId(app.getName())
if (!app.requestSingleInstanceLock()) { if (!app.requestSingleInstanceLock()) {
@ -47,14 +50,12 @@ app.whenReady().then(createWindow)
app.on('window-all-closed', () => { app.on('window-all-closed', () => {
win = null win = null
if (process.platform !== 'darwin') { if (process.platform !== 'darwin') app.quit()
app.quit()
}
}) })
app.on('second-instance', () => { app.on('second-instance', () => {
if (win) { if (win) {
// Someone tried to run a second instance, we should focus our window. // Focus on the main window if the user tried to open another
if (win.isMinimized()) win.restore() if (win.isMinimized()) win.restore()
win.focus() win.focus()
} }

View File

@ -1,5 +1,5 @@
/** /**
* Use 'electron-store' sample code. * Example of 'electron-store' usage.
*/ */
import { ipcMain } from 'electron' import { ipcMain } from 'electron'
import Store from 'electron-store' import Store from 'electron-store'
@ -7,11 +7,13 @@ import Store from 'electron-store'
/** /**
* Expose 'electron-store' to Renderer-process through 'ipcMain.handle' * Expose 'electron-store' to Renderer-process through 'ipcMain.handle'
*/ */
const store = new Store const store = new Store()
ipcMain.handle('electron-store', async (_evnet, methodSign: string, ...args: any[]) => { ipcMain.handle(
'electron-store',
async (_evnet, methodSign: string, ...args: any[]) => {
if (typeof (store as any)[methodSign] === 'function') { if (typeof (store as any)[methodSign] === 'function') {
return (store as any)[methodSign](...args) return (store as any)[methodSign](...args)
} }
return (store as any)[methodSign] return (store as any)[methodSign]
}) }
)

View File

@ -3,21 +3,20 @@ import { contextBridge, ipcRenderer } from 'electron'
import { domReady } from './utils' import { domReady } from './utils'
import { useLoading } from './loading' import { useLoading } from './loading'
const isDev = process.env.NODE_ENV === 'development'
const { appendLoading, removeLoading } = useLoading() const { appendLoading, removeLoading } = useLoading()
; (async () => { ;(async () => {
await domReady() await domReady()
appendLoading() appendLoading()
})(); })()
// --------- Expose some API to Renderer process. --------- // --------- Expose some API to the Renderer process. ---------
contextBridge.exposeInMainWorld('fs', fs) contextBridge.exposeInMainWorld('fs', fs)
contextBridge.exposeInMainWorld('removeLoading', removeLoading) contextBridge.exposeInMainWorld('removeLoading', removeLoading)
contextBridge.exposeInMainWorld('ipcRenderer', withPrototype(ipcRenderer)) contextBridge.exposeInMainWorld('ipcRenderer', withPrototype(ipcRenderer))
// `exposeInMainWorld` can not detect `prototype` attribute and methods, manually patch it. // `exposeInMainWorld` can't detect attributes and methods of `prototype`, manually patching it.
function withPrototype(obj: Record<string, any>) { function withPrototype(obj: Record<string, any>) {
const protos = Object.getPrototypeOf(obj) const protos = Object.getPrototypeOf(obj)
@ -25,7 +24,7 @@ function withPrototype(obj: Record<string, any>) {
if (Object.prototype.hasOwnProperty.call(obj, key)) continue if (Object.prototype.hasOwnProperty.call(obj, key)) continue
if (typeof value === 'function') { if (typeof value === 'function') {
// Some native API not work in Renderer-process, like `NodeJS.EventEmitter['on']`. Wrap a function patch it. // Some native APIs, like `NodeJS.EventEmitter['on']`, don't work in the Renderer process. Wrapping them into a function.
obj[key] = function (...args: any) { obj[key] = function (...args: any) {
return value.call(obj, ...args) return value.call(obj, ...args)
} }

View File

@ -1,5 +1,3 @@
/** /**
* https://tobiasahlin.com/spinkit * https://tobiasahlin.com/spinkit
* https://connoratherton.com/loaders * https://connoratherton.com/loaders

View File

@ -1,7 +1,8 @@
/** Document ready */
/** docoment ready */ export const domReady = (
export function domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) { condition: DocumentReadyState[] = ['complete', 'interactive']
return new Promise(resolve => { ) => {
return new Promise((resolve) => {
if (condition.includes(document.readyState)) { if (condition.includes(document.readyState)) {
resolve(true) resolve(true)
} else { } else {

View File

@ -15,7 +15,7 @@ render(
console.log('fs', window.fs) console.log('fs', window.fs)
console.log('ipcRenderer', window.ipcRenderer) console.log('ipcRenderer', window.ipcRenderer)
// Use ipcRenderer.on // Usage of ipcRenderer.on
window.ipcRenderer.on('main-process-message', (_event, ...args) => { window.ipcRenderer.on('main-process-message', (_event, ...args) => {
console.log('[Receive Main-process message]:', ...args) console.log('[Receive Main-process message]:', ...args)
}) })

View File

@ -1,4 +1,4 @@
// Use 'electron-store' // Usage of 'electron-store'
const store = { const store = {
async get(key: string) { async get(key: string) {
const { invoke } = window.ipcRenderer const { invoke } = window.ipcRenderer

View File

@ -5,7 +5,9 @@ import react from '@vitejs/plugin-react'
import resolve from 'vite-plugin-resolve' import resolve from 'vite-plugin-resolve'
import pkg from '../../package.json' import pkg from '../../package.json'
// https://vitejs.dev/config/ /**
* @see https://vitejs.dev/config/
*/
export default defineConfig({ export default defineConfig({
mode: process.env.NODE_ENV, mode: process.env.NODE_ENV,
root: __dirname, root: __dirname,
@ -13,11 +15,12 @@ export default defineConfig({
react(), react(),
resolveElectron( resolveElectron(
/** /**
* you can custom other module in here * Here you can specify other modules
* 🚧 need to make sure custom-resolve-module in `dependencies`, that will ensure that the electron-builder can package them correctly * 🚧 You have to make sure that your module is in `dependencies` and not in the` devDependencies`,
* which will ensure that the electron-builder can package it correctly
* @example * @example
* { * {
* 'electron-store': 'const Store = require("electron-store"); export defalut Store;', * 'electron-store': 'const Store = require("electron-store"); export default Store;',
* } * }
*/ */
), ),
@ -30,7 +33,7 @@ export default defineConfig({
resolve: { resolve: {
alias: { alias: {
'@': join(__dirname, 'src'), '@': join(__dirname, 'src'),
'src': join(__dirname, '../../src'), src: join(__dirname, '../../src'),
}, },
}, },
server: { server: {
@ -39,12 +42,18 @@ export default defineConfig({
}, },
}) })
// ------- For use Electron, NodeJs in Renderer-process ------- /**
// https://github.com/caoxiemeihao/electron-vue-vite/issues/52 * For usage of Electron and NodeJS APIs in the Renderer process
export function resolveElectron(resolves: Parameters<typeof resolve>[0] = {}): Plugin { * @see https://github.com/caoxiemeihao/electron-vue-vite/issues/52
const builtins = builtinModules.filter(t => !t.startsWith('_')) */
export function resolveElectron(
resolves: Parameters<typeof resolve>[0] = {}
): Plugin {
const builtins = builtinModules.filter((t) => !t.startsWith('_'))
// https://github.com/caoxiemeihao/vite-plugins/tree/main/packages/resolve#readme /**
* @see https://github.com/caoxiemeihao/vite-plugins/tree/main/packages/resolve#readme
*/
return resolve({ return resolve({
electron: electronExport(), electron: electronExport(),
...builtinModulesExport(builtins), ...builtinModulesExport(builtins),
@ -54,7 +63,7 @@ export function resolveElectron(resolves: Parameters<typeof resolve>[0] = {}): P
function electronExport() { function electronExport() {
return ` return `
/** /**
* All exports module see https://www.electronjs.org -> API -> Renderer Process Modules * For all exported modules see https://www.electronjs.org/docs/latest/api/clipboard -> Renderer Process Modules
*/ */
const electron = require("electron"); const electron = require("electron");
const { const {
@ -85,20 +94,25 @@ export function resolveElectron(resolves: Parameters<typeof resolve>[0] = {}): P
} }
function builtinModulesExport(modules: string[]) { function builtinModulesExport(modules: string[]) {
return modules.map((moduleId) => { return modules
.map((moduleId) => {
const nodeModule = require(moduleId) const nodeModule = require(moduleId)
const requireModule = `const M = require("${moduleId}");` const requireModule = `const M = require("${moduleId}");`
const exportDefault = `export default M;` const exportDefault = `export default M;`
const exportMembers = Object.keys(nodeModule).map(attr => `export const ${attr} = M.${attr}`).join(';\n') + ';' const exportMembers =
Object.keys(nodeModule)
.map((attr) => `export const ${attr} = M.${attr}`)
.join(';\n') + ';'
const nodeModuleCode = ` const nodeModuleCode = `
${requireModule} ${requireModule}
${exportDefault} ${exportDefault}
${exportMembers} ${exportMembers}
` `
return { [moduleId]: nodeModuleCode } return { [moduleId]: nodeModuleCode }
}).reduce((memo, item) => Object.assign(memo, item), {}) })
.reduce((memo, item) => Object.assign(memo, item), {})
} }
} }