Skip to content

第4章:Electron 核心文件解析

4.1 package.json(Electron项目配置核心)

package.json 是 Electron 项目的配置核心,它不仅包含了项目的基本信息,还定义了 Electron 应用的启动方式和依赖管理。

4.1.1 核心字段解析

main 字段

  • 作用:指定主进程入口文件
  • 默认值:如果未指定,Electron 会尝试加载 index.js
  • 示例
    json
    "main": "main.js"

scripts 字段

  • 作用:配置项目的脚本命令
  • 常用脚本
    • start:启动 Electron 应用
    • build:打包应用
    • dev:开发模式启动
  • 示例
    json
    "scripts": {
      "start": "electron .",
      "dev": "electron .",
      "build": "electron-builder"
    }

devDependencies 与 dependencies

  • devDependencies:开发依赖,如 Electron、构建工具等
  • dependencies:运行时依赖,应用运行时需要的包
  • 示例
    json
    "devDependencies": {
      "electron": "^28.0.0",
      "electron-builder": "^24.0.0"
    },
    "dependencies": {
      "axios": "^1.0.0",
      "electron-store": "^8.0.0"
    }

Electron 专属配置

  • description:应用描述
  • author:作者信息
  • license:许可证
  • productName:应用名称(显示在窗口标题栏)
  • version:应用版本

4.1.2 完整示例

json
{
  "name": "my-electron-app",
  "version": "1.0.0",
  "description": "My Electron application",
  "main": "main.js",
  "productName": "My App",
  "author": "Your Name",
  "license": "MIT",
  "scripts": {
    "start": "electron .",
    "dev": "electron .",
    "build": "electron-builder"
  },
  "devDependencies": {
    "electron": "^28.0.0",
    "electron-builder": "^24.0.0"
  },
  "dependencies": {
    "axios": "^1.0.0",
    "electron-store": "^8.0.0"
  }
}

4.2 主进程入口文件(main.js)

main.js 是 Electron 应用的主进程入口文件,负责创建窗口、控制应用生命周期和访问原生 API。

4.2.1 核心模块

app 模块

  • 作用:控制应用的生命周期
  • 常用方法
    • app.whenReady():应用就绪时触发
    • app.quit():退出应用
    • app.on('event', callback):监听应用事件
  • 常用事件
    • ready:应用就绪
    • window-all-closed:所有窗口关闭
    • activate:应用被激活

BrowserWindow 类

  • 作用:创建和控制浏览器窗口
  • 构造参数
    • width:窗口宽度
    • height:窗口高度
    • webPreferences:网页设置
    • icon:窗口图标
    • title:窗口标题
  • 常用方法
    • loadFile():加载本地 HTML 文件
    • loadURL():加载远程 URL
    • show():显示窗口
    • hide():隐藏窗口
    • close():关闭窗口
    • webContents.openDevTools():打开开发者工具

4.2.2 基本结构

javascript
const { app, BrowserWindow } = require('electron')

// 创建窗口函数
function createWindow () {
  // 创建浏览器窗口
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  })
  
  // 加载 index.html
  win.loadFile('index.html')
  
  // 打开开发者工具
  win.webContents.openDevTools()
}

// 应用就绪后创建窗口
app.whenReady().then(() => {
  createWindow()
  
  // macOS 特定处理
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// 关闭所有窗口时退出应用(Windows & Linux)
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

4.2.3 窗口配置详解

javascript
const win = new BrowserWindow({
  // 窗口大小
  width: 800,
  height: 600,
  
  // 窗口位置
  x: 100,
  y: 100,
  
  // 窗口样式
  frame: true, // 是否显示边框
  titleBarStyle: 'default', // 标题栏样式
  resizable: true, // 是否可调整大小
  maximizable: true, // 是否可最大化
  minimizable: true, // 是否可最小化
  closable: true, // 是否可关闭
  
  // 窗口图标
  icon: __dirname + '/assets/icon.png',
  
  // 窗口标题
  title: 'My Electron App',
  
  // 网页设置
  webPreferences: {
    nodeIntegration: true, // 是否启用 Node.js 集成
    contextIsolation: false, // 是否启用上下文隔离
    preload: __dirname + '/preload.js', // 预加载脚本
    devTools: true // 是否启用开发者工具
  }
})

4.3 渲染进程页面(index.html/index.js)

渲染进程页面负责应用的用户界面,包括 HTML 结构、CSS 样式和前端 JavaScript 逻辑。

4.3.1 index.html

html
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>My Electron App</title>
  <style>
    /* CSS 样式 */
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 20px;
      background-color: #f0f0f0;
    }
    h1 {
      color: #333;
    }
  </style>
</head>
<body>
  <h1>Hello Electron!</h1>
  <p>Welcome to your Electron application.</p>
  
  <!-- 页面内容 -->
  <div id="app">
    <button id="btn-click">Click Me</button>
    <div id="message"></div>
  </div>
  
  <!-- 渲染进程脚本 -->
  <script src="renderer.js"></script>
</body>
</html>

4.3.2 renderer.js(渲染进程脚本)

javascript
// 渲染进程脚本
const { ipcRenderer } = require('electron')

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
  // 按钮点击事件
  document.getElementById('btn-click').addEventListener('click', () => {
    // 向主进程发送消息
    ipcRenderer.send('button-clicked', 'Hello from renderer')
  })
  
  // 监听主进程的回复
  ipcRenderer.on('message-from-main', (event, data) => {
    document.getElementById('message').textContent = data
  })
})

4.4 实操案例:修改核心配置

4.4.1 场景描述

创建一个具有以下功能的 Electron 应用:

  • 自定义应用窗口大小和位置
  • 设置应用图标
  • 配置应用标题
  • 实现窗口关闭时的确认提示
  • 添加菜单和托盘

4.4.2 实现步骤

  1. 修改 package.json
json
{
  "name": "custom-electron-app",
  "version": "1.0.0",
  "description": "Custom Electron application",
  "main": "main.js",
  "productName": "Custom App",
  "scripts": {
    "start": "electron ."
  },
  "devDependencies": {
    "electron": "^28.0.0"
  }
}
  1. 修改 main.js
javascript
const { app, BrowserWindow, Menu, Tray, dialog } = require('electron')
const path = require('path')

let mainWindow
let tray

function createWindow () {
  // 创建浏览器窗口
  mainWindow = new BrowserWindow({
    width: 900,
    height: 600,
    x: 100,
    y: 100,
    icon: path.join(__dirname, 'assets', 'icon.png'),
    title: 'Custom Electron App',
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  })
  
  // 加载 index.html
  mainWindow.loadFile('index.html')
  
  // 打开开发者工具
  mainWindow.webContents.openDevTools()
  
  // 窗口关闭事件
  mainWindow.on('close', (event) => {
    // 取消默认关闭行为
    event.preventDefault()
    
    // 显示确认对话框
    dialog.showMessageBox({
      type: 'question',
      title: '确认关闭',
      message: '确定要关闭应用吗?',
      buttons: ['取消', '确定'],
      defaultId: 0
    }).then((result) => {
      if (result.response === 1) {
        mainWindow.destroy()
      }
    })
  })
}

// 创建菜单
function createMenu () {
  const template = [
    {
      label: '文件',
      submenu: [
        {
          label: '新建',
          accelerator: 'CmdOrCtrl+N',
          click: () => console.log('新建')
        },
        {
          label: '打开',
          accelerator: 'CmdOrCtrl+O',
          click: () => console.log('打开')
        },
        { type: 'separator' },
        {
          label: '退出',
          accelerator: 'CmdOrCtrl+Q',
          click: () => app.quit()
        }
      ]
    },
    {
      label: '编辑',
      submenu: [
        { role: 'undo' },
        { role: 'redo' },
        { type: 'separator' },
        { role: 'cut' },
        { role: 'copy' },
        { role: 'paste' }
      ]
    },
    {
      label: '帮助',
      submenu: [
        {
          label: '关于',
          click: () => console.log('关于')
        }
      ]
    }
  ]
  
  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}

// 创建托盘
function createTray () {
  tray = new Tray(path.join(__dirname, 'assets', 'tray.png'))
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '显示窗口',
      click: () => mainWindow.show()
    },
    {
      label: '退出',
      click: () => app.quit()
    }
  ])
  tray.setToolTip('Custom Electron App')
  tray.setContextMenu(contextMenu)
  
  // 点击托盘显示/隐藏窗口
  tray.on('click', () => {
    if (mainWindow.isVisible()) {
      mainWindow.hide()
    } else {
      mainWindow.show()
    }
  })
}

app.whenReady().then(() => {
  createWindow()
  createMenu()
  createTray()
  
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})
  1. 修改 index.html
html
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Custom Electron App</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 20px;
      background-color: #f5f5f5;
    }
    .container {
      max-width: 800px;
      margin: 0 auto;
      background-color: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    h1 {
      color: #333;
      text-align: center;
    }
    p {
      color: #666;
      line-height: 1.6;
    }
    .features {
      margin-top: 30px;
    }
    .feature-item {
      margin: 10px 0;
      padding: 10px;
      background-color: #f9f9f9;
      border-radius: 4px;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>Custom Electron App</h1>
    <p>这是一个自定义配置的 Electron 应用,具有以下特性:</p>
    
    <div class="features">
      <div class="feature-item">✓ 自定义窗口大小和位置</div>
      <div class="feature-item">✓ 自定义应用图标</div>
      <div class="feature-item">✓ 自定义应用标题</div>
      <div class="feature-item">✓ 窗口关闭确认提示</div>
      <div class="feature-item">✓ 自定义菜单</div>
      <div class="feature-item">✓ 系统托盘支持</div>
    </div>
  </div>
</body>
</html>
  1. 创建资源文件夹和图标
  • 创建 assets 文件夹
  • 添加 icon.png(应用图标)
  • 添加 tray.png(托盘图标)

4.4.3 运行效果

  1. 启动应用

    bash
    npm start
  2. 观察效果

    • 应用窗口以指定大小和位置打开
    • 窗口显示自定义图标和标题
    • 菜单栏显示自定义菜单
    • 系统托盘显示应用图标
    • 关闭窗口时显示确认对话框

4.5 小结

通过本章的学习,你已经了解了 Electron 核心文件的结构和配置:

  • package.json:项目配置核心,定义应用信息和脚本
  • main.js:主进程入口,控制应用生命周期和窗口
  • index.html/index.js:渲染进程页面,负责用户界面和交互

这些文件构成了 Electron 应用的基础框架,掌握它们的配置和使用方法是开发 Electron 应用的关键。在接下来的章节中,我们将学习窗口操作、进程间通信等核心功能。

© 2026 编程马·菜鸟教程 版权所有