跪拜 Guibai
← Back to the summary

A Production-Ready Electron 25+ Config Stack, Hardened for Medical Desktop Apps

Electron Full-Dimensional Complete Configuration Manual (Latest Stable Version, Adapted for Electron 25+)

Overall divided into 5 core modules:

  1. package.json project basic configuration (entry, dependencies, scripts, packaging basics)
  2. Main process app global lifecycle configuration (global system parameters)
  3. BrowserWindow window full configuration (window appearance, size, behavior)
  4. webPreferences renderer process security / capability complete configuration (top priority)
  5. Packaging configuration (electron-builder full parameters) + debugging / advanced configuration

Adapted for a previous medical bed desktop system (recording, multi-window, Vue3, permission control, CSP, audio/video).


1. package.json Top-Level Configuration (Project Root)

Basic Required Fields

json

{
  "name": "hospital-bed-system",
  "version": "1.0.0",
  "main": "./electron/main.js", // Electron entry file, must be filled in
  "description": "Hospital Bed Round Desktop System",
  "author": "xxx",
  "license": "MIT",
  "homepage": "./",
  "private": true,
  "scripts": {
    "dev": "electron .", // Local development startup
    "build": "electron-builder", // Full platform packaging
    "build-win": "electron-builder --win",
    "build-mac": "electron-builder --mac",
    "build-linux": "electron-builder --linux",
    "pack": "electron-builder --dir" // Package green file directory
  },
  "dependencies": {}, // Business runtime dependencies (fs, path, recording, serial port, etc. go here)
  "devDependencies": {
    "electron": "^30.0.0",
    "electron-builder": "^24.13.0"
  }
}

Key Field Descriptions

Table

Field Description
main Mandatory, main process entry path, Electron cannot start without it
name Software internal ID, no Chinese or spaces, packaging installation directory named after this
version Version number, upgrades and updates depend on this version
scripts Development and packaging commands, common to Windows/mac

Optional Extended Configuration

json

"electron-rebuild": {},
"type": "commonjs", // Electron defaults to commonjs; change to module for ESModule
"repository": { "type": "git", "url": "" },
"keywords": ["electron", "medical", "round", "recording"]

2. Main Process app Global Configuration (Global APIs in main.js)

app controls the entire software lifecycle, system permissions, and global parameters. All configurations are written in the main process.

2.1 app Configurable Properties (Read/Write)

Table

Property Type Default Function
app.name string package.json name Modify application system display name
app.version string package.json version Read-only, get version
app.userAgentFallback string Chromium default Global UA, adapt to intranet interfaces, hotlink protection
app.accessibilitySupportEnabled boolean false Enable system accessibility (screen reader), high performance cost
app.applicationMenu Menu/null System default menu Globally replace top menu bar; assign null to hide system menu bar
app.badgeCount number 0 Windows/mac taskbar badge number (unread bed reminders)
app.commandLine CommandLine - Chromium underlying command line startup parameters (most commonly used advanced configuration)

commandLine High-Frequency Configuration (Adapted for recording, hardware, audio/video)

js

Run

const { app } = require('electron')
// Global startup parameters, must be written before app.whenReady()
app.commandLine.appendSwitch('disable-gpu-sandbox') // Resolve Windows sound card, microphone sandbox interception
app.commandLine.appendSwitch('enable-speech-dispatcher') // Speech recognition enhancement
app.commandLine.appendSwitch('allow-file-access-from-files') // Local file cross-origin
app.commandLine.appendSwitch('autoplay-policy', 'no-user-gesture-required') // Recording/audio autoplay without click
app.commandLine.appendSwitch('ignore-certificate-errors') // Allow intranet HTTPS certificate errors

2.2 app Global Lifecycle Events (Configuration Logic Mount Points)

js

Run

// Software initialization complete, the only time to create windows
app.whenReady().then(async () => {})

// All windows closed
app.on('window-all-closed', () => {
  // macOS does not quit by default when closing, Windows quits directly
  if (process.platform !== 'darwin') app.quit()
})

// macOS click Dock icon, recreate window when no windows exist
app.on('activate', () => {})

// Software about to quit
app.on('before-quit', () => {
  // Round recording wrap-up, save audio, close microphone
})

// Capture all web request certificate errors (essential for intranet)
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
  event.preventDefault()
  callback(true) // Trust intranet self-signed certificates
})

2.3 app Path Configuration (Unified Resource Directory)

js

Run

// Get various system directories for storing recording files, logs, cache
app.getPath('userData') // Software persistent directory (recording cache, bed configuration)
app.getPath('desktop') // Desktop
app.getPath('documents') // Documents (recommended for storing round recordings)
app.setPath('userData', 'D:/hospital/cache') // Custom cache directory

3. BrowserWindow Window Complete Configuration (new BrowserWindow (options))

Complete categorized list, prioritized by usage, adapted for multi-bed windows, dual theme green/blue, white screen optimization

3.1 Basic Size & Position

js

Run

const mainWin = new BrowserWindow({
  // Size
  width: 1400,
  height: 850,
  minWidth: 1000, // Minimum width, prevent card squeeze disorder
  minHeight: 650,
  maxWidth: 2560,
  maxHeight: 1600,
  resizable: true, // Allow window resize by dragging

  // Position
  x: 200,
  y: 100,
  center: true, // Center window on screen, priority over x/y

  // Window display control (solve white screen)
  show: false, // Do not render by default, display after page loads
  backgroundColor: '#ffffff', // Background color, green mode #eaffef, round blue #e6f0ff
})
// Show after page is fully rendered, eliminate white screen
mainWin.once('ready-to-show', () => {
  mainWin.show()
})

3.2 Window Appearance, Title, Icon, Border

Table

Parameter Type Description
title string Window title, can be dynamically modified win.setTitle()
icon string Window icon, must be png/ico; Windows uses ico, mac uses icns
frame boolean false frameless window (custom navigation bar), default true
transparent boolean Window transparent, used with frame:false for rounded corners
titleBarStyle default/hidden/hiddenInset mac only; hidden hides title bar, keeps traffic lights
trafficLightPosition {x,y} mac traffic light button position offset
roundedCorners boolean Windows window rounded corner switch

3.3 Fullscreen, Topmost, Taskbar, Behavior Control

js

Run

fullscreen: false, // Fullscreen
fullscreenable: true, // Allow F11 fullscreen
alwaysOnTop: false, // Window topmost (round popup topmost)
skipTaskbar: false, // Do not show in taskbar
closable: true, minimizable: true, maximizable: true, // Button availability
hasShadow: true, // Window shadow
movable: true, // Window draggable

3.4 Mouse, Keyboard, Menu

js

Run

disableAutoHideCursor: false,
autoHideMenuBar: true, // Show top menu only when pressing Alt, hide by default (recommended)
menu: null, // Custom current window menu; null = no menu
kiosk: false, // Lock screen kiosk mode (usable for hospital touch screens)

3.5 Other Advanced Window Configuration

js

Run

parent: null, // Parent window (patient detail popup mounted to main window)
modal: false, // Modal popup, lock parent window
webContentsPreferences: {}, // Global web preference fallback
paintWhenInitiallyHidden: true,
darkTheme: false, // Follow system dark mode

4. webPreferences Most Complete Configuration (Electron Security Core, Must Read Carefully, Adapted for Recording / Vue/IPC)

Complete fields + default values + security recommendations, divided into Security Control, Node Permissions, Audio/Video, Network, Rendering, Debugging 6 categories

js

Run

webPreferences: {
  // ========== Security Red Lines (Strictly Follow in Production) ==========
  nodeIntegration: false,
  // Disable renderer page directly requiring Node; true has remote page injection risk
  contextIsolation: true,
  // Context isolation, page JS and preload completely isolated, Electron officially strongly recommends enabling
  sandbox: true,
  // Chromium sandbox; disables nodeIntegration by default when enabled, Electron20+ defaults to true
  webSecurity: true,
  // Enable same-origin policy; closing opens all CORS, high risk, temporarily close for intranet debugging

  // ========== Node Extended Permissions (Not Recommended to Enable) ==========
  nodeIntegrationInWorker: false, // WebWorker enables Node
  nodeIntegrationInSubFrames: false, // iframe enables Node
  enableRemoteModule: false, // Deprecated remote module, prohibit use, use IPC instead

  // ========== Preload (Only Secure Communication Scheme) ==========
  preload: path.join(__dirname, './preload.js'),
  // Preload script path, all main process communication, microphone permissions, file read/write expose APIs here

  // ========== Network, Cross-Origin, Certificate, Resource Loading ==========
  allowRunningInsecureContent: false,
  // Prohibit HTTPS pages loading HTTP resources; set true if intranet interfaces must enable
  allowDisplayingInsecureContent: false,
  images: true, // Load images
  javascript: true, // Enable JS, frontend project must be true
  plugins: false, // Disable Flash and other plugins
  defaultEncoding: 'UTF-8', // Default encoding, change to UTF-8 to avoid garbled text

  // ========== Audio/Video, Recording, Multimedia (Adapted for round voice recording) ==========
  autoplayPolicy: 'no-user-gesture-required',
  // Audio autoplay policy: allow automatic recording, playback, no user click required
  mediaControls: true, // System media shortcuts
  disableHtmlFullscreen: false,
  imageAnimationPolicy: 'animate', // GIF: animate/animateOnce/noAnimation

  // ========== Cache, Session, Storage ==========
  partition: 'persist:hospital',
  // Persistent session, multi-window share cookie, localStorage; without persist = memory temporary storage
  session: null, // Priority over partition, custom session object
  spellcheck: false, // Disable spell check, reduce performance consumption
  zoomFactor: 1.0, // Page zoom ratio

  // ========== Hardware, Rendering, GPU ==========
  webgl: true,
  backgroundThrottling: false,
  // Do not limit timers when window is in background; round background recording must disable throttling to prevent recording interruption
  offscreen: false, // Offscreen rendering (for screenshots, screen recording)

  // ========== Debugging, Development Configuration ==========
  devTools: process.env.NODE_ENV === 'development',
  // Directly disable developer tools in production environment to prevent tampering
  experimentalFeatures: false, // Disable Chromium experimental features
  enableWebSQL: false, // Disable deprecated WebSQL
}

4.1 Recommended Security Best Combination for Medical Systems (Copy Directly)

js

Run

webPreferences: {
  nodeIntegration: false,
  contextIsolation: true,
  sandbox: true,
  webSecurity: true,
  backgroundThrottling: false,
  autoplayPolicy: "no-user-gesture-required",
  preload: path.join(__dirname, "preload.js")
}

All microphone recording, file read/write, IPC calls are exposed in preload using contextBridge:

js

Run

// preload.js
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('electronAPI', {
  startRecord: () => ipcRenderer.invoke('record-start'),
  stopRecord: () => ipcRenderer.invoke('record-stop')
})

4.2 Temporary Configuration for Intranet Debugging (Development Only, Must Restore Security Config for Packaging)

js

Run

// Convenient for Vue debugging during development, must restore for packaging
nodeIntegration: true,
contextIsolation: false,
sandbox: false,
webSecurity: false

5. electron-builder Complete Packaging Configuration (package.json Top-Level build Field)

Windows, macOS, Linux full platform parameters, adapted for hospital intranet packaging, icons, installation paths, permissions

json

"build": {
  "appId": "com.hospital.bedsystem",
  "productName": "病床查房管理系统", // Installation package display Chinese name
  "files": [
    "electron/**/*",
    "dist/**/*",
    "node_modules/**/*"
  ],
  "extraResources": [
    "./assets/**"
  ],
  "directories": {
    "output": "release", // Packaging output directory
    "buildResources": "build" // Icon resource directory
  },
  "asar": true, // Code packaged asar encryption; false allows source code extraction
  "asarUnpack": ["node_modules/ffmpeg/**"], // Audio/video dependencies not unpacked

  // Windows specific configuration
  "win": {
    "target": [
      {
        "target": "nsis", // Installer; optional portable
        "arch": ["x64"]
      }
    ],
    "icon": "build/icon.ico",
    "requestExecutionLevel": "asInvoker", // Permission: administrator
    "publisherName": "Hospital IT Department"
  },
  "nsis": {
    "oneClick": false, // No one-click install, allow choosing installation path
    "allowToChangeInstallationDirectory": true,
    "installerIcon": "build/icon.ico",
    "uninstallerIcon": "build/icon.ico",
    "shortcutName": "Bed Round System",
    "createDesktopShortcut": true,
    "createStartMenuShortcut": true
  },

  // Mac configuration
  "mac": {
    "target": ["dmg", "zip"],
    "icon": "build/icon.icns",
    "hardenedRuntime": true,
    "entitlements": "build/entitlements.mac.plist",
    "entitlementsInherit": "build/entitlements.mac.plist"
  },

  // Linux
  "linux": {
    "target": ["deb", "rpm"],
    "icon": "build/icon.png",
    "category": "Utility"
  },

  // Auto update
  "publish": [
    {
      "provider": "generic",
      "url": "http://intranet-server/update/"
    }
  ]
}

6. Supporting Common Configuration File List

6.1 .env Environment Variables Distinguishing Development / Production

env

# .env.development
NODE_ENV=development
VITE_DEV_SERVER_URL=http://localhost:5173

# .env.production
NODE_ENV=production

Main process reads environment variables to distinguish whether to open debugging tools, whether to relax cross-origin.

6.2 .vscode/launch.json Electron Debugging Complete Configuration

json

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug Electron Main Process",
      "type": "node",
      "request": "launch",
      "cwd": "${workspaceFolder}",
      "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
      "windows": {
        "runtimeExecutable": "${workspaceFolder}/node_modules/electron/dist/electron.exe"
      },
      "args": ["."],
      "console": "integratedTerminal",
      "sourceMaps": true,
      "envFile": "${workspaceFolder}/.env.development"
    }
  ]
}

6.3 Global Menu Configuration Menu

js

Run

const { Menu } = require('electron')
// Clear default menu
Menu.setApplicationMenu(null)
// Custom minimal menu (only keep refresh, developer tools)
const template = [
  {
    label: 'View',
    submenu: [
      {role: 'reload', label:'Refresh'},
      {role: 'toggleDevTools', label:'Developer Tools'}
    ]
  }
]
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)

7. Custom Configuration Summary for Bed Round System

1. Must-Enable Recording Configuration

2. Dual Theme Green / Blue Adaptation

3. Multi-Window (Main List + Patient Detail)

4. Intranet Compatibility Configuration

5. Security Hard Constraints


8. Configuration Troubleshooting Quick Reference Table

  1. Microphone cannot capture audio: Check sandbox, commandLine sound card parameters, autoplayPolicy
  2. Vue page require error: Security three configurations (nodeIntegration/contextIsolation/sandbox) conflict
  3. Background recording stream interruption: backgroundThrottling must be false
  4. Local file cross-origin error: allow-file-access-from-files command line switch
  5. White screen after packaging: Path must use path.resolve, asar packaged resource path correct
  6. IPC communication failure: Context isolation, can only call ipcRenderer in preload