示例工程 01-what-is-electron
01-what-is-electron/demo-01-minimal-window/main.ts
import { app, BrowserWindow } from "electron";
const smoke =
process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const html = `<!doctype html>
<html lang="zh-CN">
<body style="font-family: system-ui, sans-serif; padding: 32px; line-height: 1.7">
<h1>Electron 最小窗口</h1>
<p>没有 Vite、没有 Forge,只有 <code>electron</code> 加一个 HTML 字符串。</p>
<p>窗口仍然是 Chromium;主进程负责创建它。</p>
</body>
</html>`;
app.whenReady().then(() => {
const window = new BrowserWindow({
width: 720,
height: 480,
show: false,
webPreferences: {
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
},
});
window.once("ready-to-show", () => {
window.show();
});
void window.loadURL(
`data:text/html;charset=utf-8,${encodeURIComponent(html)}`,
);
if (smoke) {
window.webContents.once("did-finish-load", () => {
const rendererPid = window.webContents.getOSProcessId();
console.log(
JSON.stringify({
evt: "smoke",
ok: rendererPid > 0,
electron: process.versions.electron,
rendererPid,
}),
);
app.quit();
});
}
});
app.on("window-all-closed", () => {
app.quit();
});