NodeJS项目使用PKG打包

前言

pkg 是一个流行的 Node.js 应用打包工具,可以将 Node.js 应用打包成单个可执行文件,支持 Windows、macOS 和 Linux 平台。

安装

1
npm install -g pkg

配置

配置中要添加下面的属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"name": "html2pdf",
"version": "1.0.0",
"main": "html2pdf.js",
"bin": {
"html2pdf": "html2pdf.js"
},
"pkg": {
"scripts": [
"node_modules/**/*.js"
],
"targets": [
"node18-win-x64"
]
},
}

打包

1
pkg .

也可以在命令中设置入口JS、目标平台和输出的文件名

1
pkg html2pdf.js --targets node18-win-x64 -o html2pdf.exe

要打包进去的JS和资源可以这样配置

1
2
3
4
5
6
7
8
"pkg": {
"scripts": [
"node_modules/**/*.js"
],
"assets": [
"dist/**/*"
]
},

测试

1
html2pdf.exe cover_url="https://www.psvmc.cn/zjtools/z/html2pdf/cover.html" content_url="http://localhost:8888/#/report_school" save_path="D:\\html2pdf\\test.pdf"

我这里打包后puppeteer不能正常用,还在找原因。