如何为 Windows 单独提供 .exe 二进制

解读

面试官问的是“如何在 npm 生态里,让 Windows 用户拿到开箱即用的 .exe 可执行文件,而不强制全平台用户都下载”。这背后考察的是平台差异化分发、包体积控制、生命周期钩子运用、以及国内开发者在 Windows 环境下的真实痛点。国内 CI 以 Windows 自托管 runner 为主,很多公司内网禁止源码编译,“绿色单文件 .exe” 是最被认可的交付形态。回答必须兼顾 npm 原生能力与国内落地经验,不能简单一句“用 pkg 打包”就结束。

知识点

  1. optionalDependencies + os/cpu 字段:利用 npm 的条件依赖解析,只在 Windows 平台下载对应的 .exe 压缩包。
  2. postinstall 钩子:在包被安装后,立即解压并重命名 .exe 到 node_modules/.bin,保证 npm run / npx 可直接调用。
  3. files 字段白名单:避免把 .exe 打进 tgz 主包,把体积留给 optionalDependency 的独立 tar.gz,减少国内镜像同步时间。
  4. 国内镜像友好:将 .exe 托管在淘宝 NPM 镜像源同域的 CDN(如 npmmirror.com 的 /binary 路径),postinstall 里优先检测 npmmirror 环境变量,失败再回源,保证内网隔离场景也能拉取。
  5. 签名与哈希:Windows Defender 在国内企业机经常误杀,必须提供 .exe 的 SHA256 校验文件,并在 postinstall 里做流式校验,失败则抛错阻断安装。
  6. lockfile 一致性:npm ci 会校验 optionalDependencies 的完整性,必须保证同一版本锁死镜像 URL,否则 CI 会频繁失效。
  7. 多架构:如果 .exe 区分 x64/arm64,在 package.json 的 cpu 数组里写清楚 ["x64", "arm64"],npm 会自动过滤。

答案

  1. 在 GitHub Releases 或国内 CDN 构建好 windows-x64.exe、windows-arm64.exe,同步上传到 npmmirror 的 /binary 路径,并生成对应的 .sha256 文件。
  2. 在项目根创建 binary 目录,放置 install.js 脚本,逻辑如下:
    a. 读取 process.platform === 'win32' 与 process.arch;
    b. 拼接 https://cdn.npmmirror.com/binaries/your-pkg/v${version}/your-${arch}.exe;
    c. 使用 https + progress-stream + sha256 做流式下载与校验;
    d. 校验通过后将 .exe 写到 path.join(__dirname, '..', 'node_modules', '.bin', 'your.exe'),并赋予 0755 权限(Windows 下由 git bash 模拟)。
  3. 在 package.json 声明:
    "optionalDependencies": {
      "your-pkg-win-x64": "https://cdn.npmmirror.com/binaries/your-pkg/1.0.0/your-win-x64.tar.gz",
      "your-pkg-win-arm64": "https://cdn.npmmirror.com/binaries/your-pkg/1.0.0/your-win-arm64.tar.gz"
    },
    "scripts": {
      "postinstall": "node binary/install.js"
    },
    "files": ["lib", "binary", "!**/*.exe"]
    
    其中 tar.gz 里仅含单一 .exe 与 .sha256,体积 < 5 MB,主包保持干净。
  4. 发布时执行 npm publish --ignore-scripts,避免 postinstall 在发布机执行;CI 里再用 npm ci --optional 验证 Windows 路径。
  5. 国内用户安装时,npm 会根据平台拉取对应的 optionalDependency,postinstall 再把 .exe 放到 .bin,实现“零配置、单文件、秒级可用”。
  6. 若用户处于 strict-ssl=false 的内网,install.js 里降级为 http+校验和 双重保险,绝不静默放行。

拓展思考

  1. pnpm 的 packageExtensions 可以强制覆盖子依赖的 optionalDependencies,在 monorepo 里统一 Windows 二进制版本,避免重复下载。
  2. 如果 .exe 需要常驻守护进程,可在 postinstall 里写 Windows Task Scheduler XML 模板,用 node-winser 一键注册服务,实现“装完即守护”。
  3. 对于Electron 场景,可把 .exe 作为 extraResource,在 electron-builder 的 nsis.include 里写 $PLUGINSDIR\your.exe,让安装包自带签名,绕过 npm 生命周期,适合国内桌面软件过白名单。
  4. 未来 npm 若落地 Registry Web Signatures,可把 .exe 的签名摘要写进 package.json 的 signatures 字段,install.js 里直接验签而不依赖外部 sha256,进一步提升供应链安全。