axios-miniprogram/scripts/build.assets.ts

54 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-03-24 19:41:17 +08:00
import fs from 'node:fs';
2023-04-28 15:35:54 +08:00
import { basename } from 'node:path';
2023-03-24 19:41:17 +08:00
import fg from 'fast-glob';
import JSZip from 'jszip';
import consola from 'consola';
import chalk from 'chalk';
2023-04-28 15:35:54 +08:00
import { distPath, exec } from './utils';
import { checkSize } from './checkSize';
2023-03-24 19:41:17 +08:00
main();
async function main() {
exec('pnpm build');
2023-04-28 15:35:54 +08:00
console.log('');
2023-04-17 14:12:52 +08:00
consola.info('Generate assets\n');
2023-03-24 19:41:17 +08:00
for (const filePath of await fg(`${distPath}/**.js`)) {
await generateZip(filePath, filePath.replace(/\.js$/, '.zip'));
}
2023-04-28 15:35:54 +08:00
checkSize(`${distPath}/**.zip`);
2023-03-24 19:41:17 +08:00
}
function generateZip(inputPath: string, outputPath: string) {
2023-03-25 14:16:10 +08:00
const start = Date.now();
2023-04-28 15:35:54 +08:00
const inputName = basename(inputPath);
const outputName = basename(outputPath);
2023-03-24 19:41:17 +08:00
2023-03-25 14:16:10 +08:00
console.log(chalk.cyanBright.bold(`${inputPath} → dist/${outputName}...`));
return new Promise((resolve, reject) => {
2023-05-14 20:55:47 +08:00
const finish = (result: any) => {
2023-03-25 14:16:10 +08:00
console.log(
`${chalk.green('created')} ${chalk.greenBright.bold(
`dist/${outputName} in ${Date.now() - start}ms\n`,
)}`,
);
exec(`rimraf ${inputPath}`);
resolve(result);
};
2023-03-24 19:41:17 +08:00
JSZip()
2023-03-24 20:15:51 +08:00
.file(inputName, fs.createReadStream(inputPath), {
compressionOptions: {
level: 9,
},
})
2023-03-24 19:41:17 +08:00
.generateNodeStream({ type: 'nodebuffer', streamFiles: true })
.pipe(fs.createWriteStream(outputPath))
2023-03-25 14:16:10 +08:00
.on('finish', finish)
2023-03-24 19:41:17 +08:00
.on('error', reject);
});
}