const fs = require('fs');
const ncp = require('ncp').ncp;
const pkg = require('./package.json');
const exec = require('child_process').exec;
// 复制依赖项和项目文件
ncp('./node_modules', './build/node_modules', function (err) {
if (err) {
return console.error(err);
}
// 复制项目文件
fs.copyFile('./app.js', './build/app.js', (err) => {
if (err) throw err;
console.log('app.js was copied to build directory');
});
// 创建.pkgdef文件
fs.writeFile('./build/pkgdef', `[requested_product_name]
${pkg.name}
[product_description]
${pkg.description}
[request_execute_file]
app.js
[product_version]
${pkg.version}
[company_name]
${pkg.author}
[copyright]
Copyright © ${new Date().getFullYear()} ${pkg.author}
[name]
${pkg.name}
[icon_file]
icon.ico
[uninstall_icon_file]
uninstall-icon.ico
[install_mode]
normal
[display_name]
${pkg.name}
[uninstall_display_name]
Uninstall ${pkg.name}
[install_dir]
[%HOME%]/${pkg.name}
[uninstall_dir]
[%HOME%]/${pkg.name}
[components]
main
[files]
+app.js
+node_modules/**/*
+package.json
`, (err) => {
if (err) throw err;
console.log('pkgdef file was created');
// 调用pkg打包
exec('pkg -t node12-win-x64 .', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
});
});
这段代码首先复制了项目依赖和入口文件app.js
到build
目录,然后创建了一个.pkgdef
文件,最后调用pkg
工具打包了项目。注意,这里假设您已经有了ncp
(一个Node.js的文件复制库)和pkg
这两个工具安装在项目的node_modules
目录中。