用Electron开发的应用程序本质是一个Node.js应用程序,但它专注的不是Web服务器端,而是桌面应用,即用Web页面做界面。你能把它看作成一个被JavaScript控制的,精简版的Chromium浏览器。
import { app, BrowserWindow, globalShortcut } from 'electron'
import * as path from 'path'
import { format as formatUrl } from 'url'
// import { electron } from 'webpack'
// utf-8-validate@^5.0.2
const isDevelopment = process.env.NODE_ENV !== 'production'
// global reference to mainWindow (necessary to prevent window from being garbage collected)
let mainWindow
function createMainWindow() {
const window = new BrowserWindow({//创建一个electron窗口
width: 800, //窗口初始宽度
height: 600, //窗口初始高度
minWidth: 800, //窗口最小的宽度
minHeight: 600, //窗口最小的高度
backgroundColor: '#02243B', //窗口背景
frame: false, //创建的窗口是否带边框
// titleBarOverlay: true,
titleBarStyle: 'hidden',
icon: '../image/platform.ico', //图标
webPreferences: {
// preload: path.join(__dirname, 'preload.js')
nodeIntegration: true, //开启node环境也就是说改为true后在页面可以使用require
contextIsolation: false, // 是否在独立 JavaScript 环境中运行
webSecurity: false, // 它将禁用同源策略 (通常用来测试网站), 如果此选项不是由开发者设置的默认为true
enableRemoteModule: true,
defaultMonospaceFontSize:16, //页面字体默认为16
minimumFontSize:12, //页面字体最小为12
v8CacheOptions:'bypassHeatCheckAndEagerCompile'//v8CacheOptions 强制 blink 使用 v8 代码缓存策略 除了编译是及时的。 默认策略是 code。
},
})
// 设置窗口菜单栏
window.setMenu(null)
// 打开 DevTools
window.webContents.openDevTools()
// const indexUrl = path.join(__dirname, '../../html/index.html')
// window.loadFile(indexUrl)
// 砍断当前是不是开发环境
if (isDevelopment) {
// 配置开发环境的路径
window.loadURL(formatUrl({
pathname: path.join(__dirname, '../../html/index.html'),
protocol: 'file',
slashes: true
}))
} else {
// 否则则为上线环境,配置路径
window.loadURL(formatUrl({
pathname: path.join(__dirname, '../html/index.html'),
protocol: 'file',
slashes: true
}))
}
//window.loadURL("http://192.168.2.48:8080/#/")
//window.loadURL("http://192.168.2.116:8080/#/")
// 浏览器在窗口关闭时触发 当你接收到这个事件的时候, 你应当移除相应窗口的引用对象,避免再次使用它.
window.on('closed', () => {
mainWindow = null
})
window.webContents.on('devtools-opened', () => {
window.focus()
setImmediate(() => {
window.focus()
})
})
return window
}
// quit application when all windows are closed
app.on('window-all-closed', () => {
// on macOS it is common for applications to stay open until the user explicitly quits
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// on macOS it is common to re-create a window even after all windows have been closed
if (mainWindow === null) {
mainWindow = createMainWindow()
}
})
// create main BrowserWindow when electron is ready
app.on('ready', () => {
mainWindow = createMainWindow()
// globalShortcut.register('F12', () => {
// mainWindow.webContents.openDevTools()
// })
})
require('@electron/remote/main').initialize()