feat(nodeIntegration): set nodeIntegration as true by default

This commit is contained in:
oceanlvr
2022-03-13 21:52:58 +08:00
parent b5bae8a607
commit 42fb116817
12 changed files with 1778 additions and 216 deletions

View File

@@ -12,6 +12,7 @@ if (!app.requestSingleInstanceLock()) {
app.quit()
process.exit(0)
}
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'
let win: BrowserWindow | null = null
@@ -19,11 +20,14 @@ async function createWindow() {
win = new BrowserWindow({
title: 'Main window',
webPreferences: {
preload: join(__dirname, '../preload/index.cjs')
preload: join(__dirname, '../preload/index.cjs'),
nodeIntegration: true,
contextIsolation: false,
},
})
if (app.isPackaged || process.env["DEBUG"]) {
if (app.isPackaged || process.env['DEBUG']) {
// Load built files in the debug mode instead of reading from vite server
win.loadFile(join(__dirname, '../renderer/index.html'))
} else {
// 🚧 Use ['ENV_NAME'] avoid vite:define plugin
@@ -33,9 +37,20 @@ async function createWindow() {
win.webContents.openDevTools()
}
// Communicate with the Renderer-process.
win.webContents.on('ipc-message', (_, channel, ...args) => {
switch (channel) {
case 'app.getPath':
win?.webContents.send('app.getPath', app.getPath(args[0]))
break
default:
break
}
})
// Test active push message to Renderer-process
win.webContents.on('did-finish-load', () => {
win?.webContents.send('main-process-message', (new Date).toLocaleString())
win?.webContents.send('main-process-message', new Date().toLocaleString())
})
// Make all links open with the browser, not with the application

View File

@@ -1,36 +1,11 @@
import fs from 'fs'
import { contextBridge, ipcRenderer } from 'electron'
import { domReady } from './utils'
import { useLoading } from './loading'
const { appendLoading, removeLoading } = useLoading()
window.removeLoading = removeLoading;
;(async () => {
await domReady()
appendLoading()
})()
// --------- Expose some API to the Renderer process. ---------
contextBridge.exposeInMainWorld('fs', fs)
contextBridge.exposeInMainWorld('removeLoading', removeLoading)
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
}
})()

View File

@@ -3,9 +3,6 @@ export { }
declare global {
interface Window {
// Expose some Api through preload script
fs: typeof import('fs')
ipcRenderer: import('electron').IpcRenderer
removeLoading: () => void
}
}

View File

@@ -1,14 +1,14 @@
import { createApp } from 'vue'
import App from './App.vue'
import ipcRendererSample from './mainModules/ipcRendererSample'
import fsExample from './mainModules/builtinModuleSample'
import sqliteExample from './mainModules/nodeModulesSample'
createApp(App)
.mount('#app')
.$nextTick(window.removeLoading)
// console.log('fs', window.fs)
// console.log('ipcRenderer', window.ipcRenderer)
// Usage of ipcRenderer.on
window.ipcRenderer.on('main-process-message', (_event, ...args) => {
console.log('[Receive Main-process message]:', ...args)
})
.$nextTick(() => {
window.removeLoading()
ipcRendererSample()
fsExample()
sqliteExample()
})

View File

@@ -0,0 +1,13 @@
import fs from 'fs';
const fsExample = () => {
fs.lstat(process.cwd(),(err,stats)=>{
if(err){
console.log(err)
}else{
console.log(stats);
}
})
}
export default fsExample

View File

@@ -0,0 +1,9 @@
import {ipcRenderer} from 'electron' // rename from cjs to esm by plugin `resolveElectron` in packages/renderer/vite.config.ts
const ipcRendererHelloWorld = () => {
// Usage of ipcRenderer.on
ipcRenderer.on('main-process-message', (_event, ...args) => {
console.log('[Receive Main-process message]:', ...args)
})
}
export default ipcRendererHelloWorld

View File

@@ -0,0 +1,31 @@
import path from 'path'
import { ipcRenderer } from 'electron'
import sqlite3 from 'sqlite3'
const createSqlite3 = (userDataPath: string): Promise<sqlite3.Database> => {
return new Promise((resolve, reject) => {
const dbpath = path.join(userDataPath, 'sqlite3.db')
console.log(dbpath)
const db = new sqlite3.Database(dbpath, (error) => {
if (error) {
reject(error)
return
}
resolve(db)
})
})
}
const sqliteExample = () => {
ipcRenderer.on('app.getPath', async (_, userDataPath) => {
try {
const db = await createSqlite3(userDataPath)
console.log(db)
} catch (error) {
console.error(error)
}
})
ipcRenderer.send('app.getPath', 'userData')
}
export default sqliteExample

View File

@@ -20,6 +20,9 @@ export default defineConfig({
* 'electron-store': 'const Store = require("electron-store"); export default Store;',
* }
*/
{
sqlite3: 'const sqlite3 = require("sqlite3"); export default sqlite3;',
},
),
],
base: './',
@@ -40,7 +43,6 @@ export function resolveElectron(
resolves: Parameters<typeof resolve>[0] = {}
): Plugin {
const builtins = builtinModules.filter((t) => !t.startsWith('_'))
/**
* @see https://github.com/caoxiemeihao/vite-plugins/tree/main/packages/resolve#readme
*/