import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
function makeCase(name, expected, actual) {
return {
name,
passed: JSON.stringify(actual) === JSON.stringify(expected),
expected,
actual,
};
}
const cases = [];
// Case 1: Node.js version baseline & minimal project scaffold creation
{
const nodeMajor = Number(process.versions.node.split('.')[0]);
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'electron-ch04-'));
try {
const pkgPath = path.join(tmpDir, 'package.json');
const mainPath = path.join(tmpDir, 'main.js');
const htmlPath = path.join(tmpDir, 'index.html');
const pkg = {
name: 'my-electron-app',
version: '1.0.0',
main: 'main.js',
scripts: { start: 'electron .' },
devDependencies: { electron: '^33.0.0' },
};
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2), 'utf8');
fs.writeFileSync(
mainPath,
"const { app, BrowserWindow } = require('electron');\napp.whenReady().then(() => new BrowserWindow({ width: 800, height: 600 }).loadFile('index.html'));\n",
'utf8',
);
fs.writeFileSync(
htmlPath,
'<!DOCTYPE html>\n<html><head><meta charset="utf-8"><title>Electron 安装验证</title></head><body><h1>Hello, Electron!</h1></body></html>',
'utf8',
);
const parsedPkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
const htmlText = fs.readFileSync(htmlPath, 'utf8');
const expected = {
nodeVersionSatisfiesLts: true,
startScript: 'electron .',
mainEntry: 'main.js',
hasHelloHeading: true,
hasSingleDoctype: true,
};
const actual = {
nodeVersionSatisfiesLts: nodeMajor >= 18,
startScript: parsedPkg.scripts.start,
mainEntry: parsedPkg.main,
hasHelloHeading: htmlText.includes('<h1>Hello, Electron!</h1>'),
hasSingleDoctype: (htmlText.match(/<!DOCTYPE html>/gi) || []).length === 1,
};
cases.push(makeCase('node_env_and_project_scaffold', expected, actual));
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
}
// Case 2: Local devDependency installation vs global install artifacts
{
const npmInstall = 'npm install electron --save-dev';
const yarnInstall = 'yarn add electron --dev';
const expectedArtifacts = ['node_modules/', 'package.json', 'package-lock.json'];
const expected = {
npmUsesDevFlag: true,
yarnUsesDevFlag: true,
artifactCount: 3,
recommendedScope: 'project-local',
};
const actual = {
npmUsesDevFlag: npmInstall.includes('--save-dev'),
yarnUsesDevFlag: yarnInstall.includes('--dev'),
artifactCount: expectedArtifacts.length,
recommendedScope: 'project-local',
};
cases.push(makeCase('install_modes_and_directory_artifacts', expected, actual));
}
// Case 3: Mirror configuration & error troubleshooting rules
{
const mirrorUrl = new URL('https://npmmirror.com/mirrors/electron/');
const diagnostics = new Map([
['npm ERR! code ELIFECYCLE', { cause: 'permission_or_cache', fix: 'npm cache clean --force' }],
['electron failed to install correctly', { cause: 'network_timeout', fix: 'ELECTRON_MIRROR' }],
]);
const expected = {
mirrorProtocol: 'https:',
mirrorHost: 'npmmirror.com',
mirrorPath: '/mirrors/electron/',
elifecycleFix: 'npm cache clean --force',
installFailFix: 'ELECTRON_MIRROR',
};
const actual = {
mirrorProtocol: mirrorUrl.protocol,
mirrorHost: mirrorUrl.hostname,
mirrorPath: mirrorUrl.pathname,
elifecycleFix: diagnostics.get('npm ERR! code ELIFECYCLE').fix,
installFailFix: diagnostics.get('electron failed to install correctly').fix,
};
cases.push(makeCase('mirror_and_troubleshooting_rules', expected, actual));
}
// Case 4: Optional tooling commands contract
{
const tools = [
{ name: 'electron-builder', cmd: 'npm install electron-builder --save-dev', purpose: 'installer' },
{ name: 'electron-reload', cmd: 'npm install electron-reload --save-dev', purpose: 'auto_reload' },
{ name: 'electron-forge', cmd: 'npx create-electron-app my-app', purpose: 'scaffold' },
];
const expected = {
toolNames: ['electron-builder', 'electron-reload', 'electron-forge'],
devDepToolsCount: 2,
forgeUsesNpx: true,
};
const actual = {
toolNames: tools.map((t) => t.name),
devDepToolsCount: tools.filter((t) => t.cmd.includes('--save-dev')).length,
forgeUsesNpx: tools[2].cmd.startsWith('npx '),
};
cases.push(makeCase('optional_toolchain_contracts', expected, actual));
}
console.log(JSON.stringify({ version: process.version, cases }));
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Node.js v24.22.3 本地运行环境。
入口文件:projects/electron-install-lab/explore-install.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-install.mjs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a1081.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1087.zip