示例工程 49-handrolled-vite-config
49-handrolled-vite-config/app/main/index.ts
import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import {
CH,
type Artifact,
type Check,
type EventRow,
type Probe,
type Snapshot,
} from "../shared/ipc";
app.setName("Handrolled Vite Lab");
const isSmoke =
process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
const tempData =
isSmoke || isShots ? path.join(os.tmpdir(), `vite49-${process.pid}`) : "";
if (tempData) app.setPath("userData", tempData);
const appRoot = app.getAppPath();
const mainDir = __dirname;
const outRoot = path.join(appRoot, "out");
const devUrl = process.env.ELECTRON_START_URL ?? "";
let win: BrowserWindow | null = null;
let events: EventRow[] = [];
let probe: Probe = {
url: "",
requireType: "unknown",
processType: "unknown",
relativeScript: false,
scriptSrcs: [],
styleCount: 0,
csp: "",
};
function log(kind: string, detail: string): void {
events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40);
broadcast();
}
function broadcast(): void {
if (win && !win.isDestroyed()) {
win.webContents.send("build:event", { at: Date.now() });
}
}
function fileInfo(relPath: string): { exists: boolean; bytes: number } {
try {
const stat = fsSync.statSync(path.join(appRoot, relPath));
return { exists: stat.isFile(), bytes: stat.size };
} catch {
return { exists: false, bytes: 0 };
}
}
function firstAsset(): string {
try {
const dir = path.join(outRoot, "renderer/assets");
const files = fsSync
.readdirSync(dir)
.filter((name) => name.endsWith(".js"))
.sort();
return files[0] ? `out/renderer/assets/${files[0]}` : "";
} catch {
return "";
}
}
function artifacts(): Artifact[] {
const main = fileInfo("out/main/index.cjs");
const preload = fileInfo("out/preload/preload.cjs");
const renderer = fileInfo("out/renderer/index.html");
const asset = firstAsset();
const assetInfo = asset ? fileInfo(asset) : { exists: false, bytes: 0 };
return [
{
target: "main",
entry: "main/index.ts",
outDir: "out/main",
format: "cjs",
external: ["electron", "node:*"],
file: "out/main/index.cjs",
exists: main.exists,
bytes: main.bytes,
sourcemap: fileInfo("out/main/index.cjs.map").exists,
},
{
target: "preload",
entry: "preload/index.ts",
outDir: "out/preload",
format: "cjs",
external: ["electron", "node:*"],
file: "out/preload/preload.cjs",
exists: preload.exists,
bytes: preload.bytes,
sourcemap: fileInfo("out/preload/preload.cjs.map").exists,
},
{
target: "renderer",
entry: "index.html",
outDir: "out/renderer",
format: "esm",
external: [],
file: asset || "out/renderer/assets",
exists: renderer.exists && assetInfo.exists,
bytes: renderer.bytes + assetInfo.bytes,
sourcemap: fileInfo(`${asset}.map`).exists,
},
];
}
function bundleHasElectronRequire(): boolean {
try {
const text = fsSync.readFileSync(
path.join(outRoot, "main/index.cjs"),
"utf8",
);
return /require\(["']electron["']\)/.test(text);
} catch {
return false;
}
}
function checks(): Check[] {
const list = artifacts();
const main = list.find((row) => row.target === "main");
const preload = list.find((row) => row.target === "preload");
const renderer = list.find((row) => row.target === "renderer");
return [
{
id: "main",
label: "main 产物存在",
pass: main?.exists === true && (main?.bytes ?? 0) > 0,
detail: `${main?.bytes ?? 0} B`,
},
{
id: "preload",
label: "preload 产物存在",
pass: preload?.exists === true && (preload?.bytes ?? 0) > 0,
detail: `${preload?.bytes ?? 0} B`,
},
{
id: "renderer",
label: "renderer HTML 与资源存在",
pass: renderer?.exists === true,
detail: renderer?.file ?? "",
},
{
id: "hash",
label: "renderer 资源带内容哈希",
pass: /assets\/[^/]+-[A-Za-z0-9_-]{8,}\.js$/.test(renderer?.file ?? ""),
detail: renderer?.file.split("/").pop() ?? "",
},
{
id: "cjs",
label: "main 以 CJS 输出并保留 require(electron)",
pass: bundleHasElectronRequire(),
detail: bundleHasElectronRequire() ? "require" : "missing",
},
{
id: "external",
label: "electron 被 external(main < 200KB)",
pass: (main?.bytes ?? 0) > 0 && (main?.bytes ?? 0) < 200_000,
detail: `${main?.bytes ?? 0} B`,
},
{
id: "preload-path",
label: "preload 路径与产物一致",
pass: fsSync.existsSync(path.join(mainDir, "../preload/preload.cjs")),
detail: "../preload/preload.cjs",
},
{
id: "base",
label: "renderer 使用相对 base(./assets)",
pass: probe.relativeScript,
detail: probe.scriptSrcs[0] ?? "none",
},
{
id: "file-url",
label: "生产态从 file:// 加载",
pass: probe.url.startsWith("file://"),
detail: probe.url.slice(0, 42),
},
{
id: "no-node",
label: "渲染进程无 require / process",
pass:
probe.requireType === "undefined" && probe.processType === "undefined",
detail: `${probe.requireType}/${probe.processType}`,
},
];
}
function snapshot(): Snapshot {
const list = checks();
const passed = list.filter((check) => check.pass).length;
return {
platform: process.platform,
electronVersion: process.versions.electron,
nodeVersion: process.versions.node,
mainDir,
appPath: appRoot,
resourcesPath: process.resourcesPath,
devUrl,
artifacts: artifacts(),
probe: { ...probe, scriptSrcs: [...probe.scriptSrcs] },
checks: list,
score: Math.round((passed / list.length) * 100),
events: events.map((row) => ({ ...row })),
};
}
async function runProbe(window: BrowserWindow): Promise<void> {
try {
const result = (await window.webContents.executeJavaScript(`(() => {
const meta = document.querySelector('meta[http-equiv="Content-Security-Policy"]');
return {
url: location.href,
requireType: typeof window.require,
processType: typeof window.process,
scriptSrcs: [...document.scripts].map((node) => node.getAttribute('src') || ''),
styleCount: document.styleSheets.length,
csp: meta ? meta.getAttribute('content') || '' : ''
};
})()`)) as Partial<Probe>;
probe = {
url: String(result.url ?? ""),
requireType: String(result.requireType ?? "unknown"),
processType: String(result.processType ?? "unknown"),
relativeScript: (result.scriptSrcs ?? []).some(
(src) => src.startsWith("./assets/") || src.startsWith("assets/"),
),
scriptSrcs: Array.isArray(result.scriptSrcs) ? result.scriptSrcs : [],
styleCount: Number(result.styleCount ?? 0),
csp: String(result.csp ?? ""),
};
log("probe", `${probe.url.slice(0, 34)} · ${probe.requireType}`);
} catch (error) {
log("probe-error", error instanceof Error ? error.message : String(error));
}
broadcast();
}
function createWindow(): BrowserWindow {
const preload = path.join(__dirname, "../preload/preload.cjs");
const window = new BrowserWindow({
width: 1100,
height: 860,
show: false,
title: "手写 Vite 配置实验室",
backgroundColor: "#ffffff",
webPreferences: {
preload,
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
webSecurity: true,
allowRunningInsecureContent: false,
experimentalFeatures: false,
webviewTag: false,
spellcheck: false,
backgroundThrottling: true,
},
});
const contents = window.webContents;
contents.setWindowOpenHandler(() => ({ action: "deny" }));
contents.on("will-navigate", (event, url) => {
if (!url.startsWith("file://") && !url.startsWith(devUrl)) {
event.preventDefault();
}
});
contents.on("will-attach-webview", (event) => event.preventDefault());
window.once("ready-to-show", () => window.show());
contents.once("did-finish-load", () => {
if (!window.isDestroyed() && !window.isVisible()) window.show();
log("ready", "手写配置界面已加载");
void runProbe(window);
});
if (devUrl) {
void window.loadURL(devUrl);
} else {
void window.loadFile(path.join(__dirname, "../renderer/index.html"));
}
win = window;
return window;
}
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function evalRenderer<T>(
window: BrowserWindow,
code: string,
): Promise<T> {
let lastCaught: unknown = null;
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
return (await window.webContents.executeJavaScript(code)) as T;
} catch (caught) {
lastCaught = caught;
await delay(150);
}
}
throw lastCaught instanceof Error
? lastCaught
: new Error(String(lastCaught));
}
async function waitForRenderer(window: BrowserWindow): Promise<void> {
for (let attempt = 0; attempt < 160; attempt += 1) {
if (window.isDestroyed()) return;
try {
const ready = await evalRenderer<boolean>(
window,
"typeof window.__demo === 'function'",
);
if (ready) return;
} catch {
// 页面仍在加载。
}
await delay(100);
}
throw new Error("renderer did not become ready");
}
type DemoState = {
score: number;
checks: number;
passed: number;
mainBytes: number;
preloadBytes: number;
rendererBytes: number;
relativeScript: boolean;
url: string;
requireType: string;
processType: string;
cjs: boolean;
preloadPath: boolean;
files: number;
};
async function runSmoke(window: BrowserWindow): Promise<void> {
try {
await waitForRenderer(window);
await delay(600);
await waitForRenderer(window);
const state = await evalRenderer<DemoState>(window, "window.__demo()");
process.stdout.write(
`${JSON.stringify({
evt: "smoke",
ok:
state.score === 100 &&
state.checks === 10 &&
state.passed === 10 &&
state.mainBytes > 0 &&
state.mainBytes < 200_000 &&
state.preloadBytes > 0 &&
state.rendererBytes > 0 &&
state.relativeScript &&
state.url.startsWith("file://") &&
state.requireType === "undefined" &&
state.processType === "undefined" &&
state.cjs &&
state.preloadPath &&
state.files === 3,
...state,
})}\n`,
);
app.quit();
} catch (caught) {
process.stdout.write(
`${JSON.stringify({ evt: "smoke", ok: false, message: String(caught) })}\n`,
);
app.exit(1);
}
}
async function capture(
window: BrowserWindow,
dir: string,
file: string,
): Promise<void> {
const image = await window.webContents.capturePage();
if (image.isEmpty()) throw new Error(`empty capture: ${file}`);
const png = image.toPNG();
fsSync.writeFileSync(path.join(dir, file), png);
fsSync.writeFileSync(path.join(dir, "raw", file), png);
}
async function runShots(window: BrowserWindow): Promise<void> {
try {
const dir = path.resolve(
process.cwd(),
"../../../docs/assets/images/49-handrolled-vite-config",
);
fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
await waitForRenderer(window);
await delay(600);
await waitForRenderer(window);
await evalRenderer(window, `window.__prepareShots("artifacts")`);
await delay(250);
await capture(window, dir, "49-01-artifacts.png");
await evalRenderer(window, `window.__prepareShots("configs")`);
await delay(250);
await capture(window, dir, "49-02-configs.png");
await evalRenderer(window, `window.__prepareShots("paths")`);
await delay(250);
await capture(window, dir, "49-03-paths.png");
app.quit();
} catch (caught) {
process.stdout.write(
`${JSON.stringify({ evt: "shots-error", message: String(caught) })}\n`,
);
app.exit(1);
}
}
ipcMain.handle(CH.snapshot, () => snapshot());
ipcMain.handle(CH.refresh, async () => {
if (win) await runProbe(win);
log("refresh", "重新读取构建产物与页面探针");
return snapshot();
});
app.whenReady().then(() => {
log("paths", `__dirname=${mainDir}`);
const window = createWindow();
if (isSmoke) {
void runSmoke(window);
} else if (isShots) {
void runShots(window);
}
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
} else {
win?.show();
win?.focus();
}
});
});
app.on("will-quit", () => {
if (tempData) {
try {
fsSync.rmSync(tempData, { recursive: true, force: true });
} catch {
// 清理失败不影响退出。
}
}
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") app.quit();
});