electron入口文件配置在package.json的main中:
我这里写的是background.js
常见的引入模块:
- app —描述整个应用程序的行为和生命周期
- BrowserWindow—应用窗口管理
- globalShortcut —快捷键的设置
- protocol —协议
'use strict'
import { app, BrowserWindow, globalShortcut, protocol } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
const isDevelopment = process.env.NODE_ENV !== 'production'
let win
// 注册协议,产品模式使用
protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { secure: true, standard: true } }])
function createWindow () {
// Create the browser window.
win = new BrowserWindow({
width: 1280,
height: 1024,
webPreferences: {
nodeIntegration: true, //允许在浏览器中运行nodejs代码
webSecurity: false // 取消跨域限制
},
kiosk: false,
// frame: true,
// fullscreen: true, //! isDevelopment,
icon: 'public/app.ico'
})
// 开启devtool调试工具
win.webContents.openDevTools()
if (process.env.WEBPACK_DEV_SERVER_URL) {
win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (process.env.IS_TEST) win.webContents.openDevTools()
} else {
// 生产模式需要自己创建协议,让相对路径的各个资源可以被访问到
createProtocol('app')
win.loadURL('app://./index.html')
}
win.on('closed', () => {
win = null
})
}
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow()
}
})
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
if (isDevelopment && !process.env.IS_TEST) {
try {
await installVueDevtools()
} catch (e) {
console.error('Vue Devtools failed to install:', e.toString())
}
}
// 在开发环境可通过快捷键打开devTools
if (Config.getInstance().isDebug() || isDevelopment) {
globalShortcut.register('CommandOrControl+Shift+i', function () {
win.webContents.openDevTools()
})
}
createWindow()
})
// node中使用process.on方法进行监听事件,如退出信号或消息(其内部实现仍是eventEmitter)
if (isDevelopment) {
if (process.platform === 'win32') {
process.on('message', data => {
if (data === 'graceful-exit') {
app.quit()
}
})
} else {
process.on('SIGTERM', () => {
app.quit()
})
}
}