- #打包#exe#pkg 使用 pkg 将 nodejs 打包编译为 exe
-
# 第一步: 安装依赖 $ pnpm install -g pkg # 第二步: 编写测试代码 app.js const fs = require('fs') function writeLog(message) { console.log('20240710153205 -------> ', message) fs.appendFileSync('alogs.txt', `${message}\n`, 'utf8') } // 示例用法 writeLog('这是一条日志') # 第三步: 编写和运行 pkg 命令 "scripts": { "build": "pkg -t win ./app.js --output ./dist/app.exe" }
- 遇到各种问题都可以通过这篇文章找到答案: https://segmentfault.com/a/1190000041958374
- 比较麻烦的报错如下:
-
> pkg -t win ./app.js --output ./dist/app.exe > pkg@5.7.0 > Fetching base Node.js binaries to PKG_CACHE_PATH fetched-v18.1.0-win-x64 [ ] 0%> Not found in remote cache: {"tag":"v3.4","name":"node-v18.1.0-win-x64"} > Building base binary from source: built-v18.1.0-win-x64 > Fetching Node.js source archive from nodejs.org... > Error! AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:
- 大意就是无法下载相关文件. 哪怕我 fq 也失败. 解决方法如下:
- https://github.com/vercel/pkg-fetch/releases, 下载你需要的版本, 譬如我是 v18.1.0-win-x64, 那么就下载 node-v18.1.0-win-x64
- 本地应当存在这个路径: C:Userslee.pkg-cachev3.4, 这个路径是 pkg 默认创建的. 将下载好的 node-v18.1.0-win-x64 放置其中, 并且重命名为 fetched-v18.1.0-win-x64
- 重新执行编译
- https://github.com/vercel/pkg-fetch/releases, 下载你需要的版本, 譬如我是 v18.1.0-win-x64, 那么就下载 node-v18.1.0-win-x64
-
- 比较麻烦的报错如下:
- 遇到各种问题都可以通过这篇文章找到答案: https://segmentfault.com/a/1190000041958374
-