|
| 1 | +import path from 'path'; |
| 2 | +import * as fs from 'fs-extra'; |
| 3 | +import { ZipFile as YazlZipFile } from 'yazl'; |
| 4 | +import { t } from './utils/i18n'; |
| 5 | + |
| 6 | +const ignorePackingFileNames = [ |
| 7 | + '.', |
| 8 | + '..', |
| 9 | + 'index.bundlejs.map', |
| 10 | + 'bundle.harmony.js.map', |
| 11 | +]; |
| 12 | +const ignorePackingExtensions = ['DS_Store', 'txt.map']; |
| 13 | + |
| 14 | +export async function packBundle(dir: string, output: string): Promise<void> { |
| 15 | + console.log(t('packing')); |
| 16 | + fs.ensureDirSync(path.dirname(output)); |
| 17 | + await new Promise<void>((resolve, reject) => { |
| 18 | + const zipfile = new YazlZipFile(); |
| 19 | + |
| 20 | + function addDirectory(root: string, rel: string) { |
| 21 | + if (rel) { |
| 22 | + zipfile.addEmptyDirectory(rel); |
| 23 | + } |
| 24 | + const children = fs.readdirSync(root); |
| 25 | + for (const name of children) { |
| 26 | + if ( |
| 27 | + ignorePackingFileNames.includes(name) || |
| 28 | + ignorePackingExtensions.some((ext) => name.endsWith(`.${ext}`)) |
| 29 | + ) { |
| 30 | + continue; |
| 31 | + } |
| 32 | + const fullPath = path.join(root, name); |
| 33 | + const stat = fs.statSync(fullPath); |
| 34 | + if (stat.isFile()) { |
| 35 | + zipfile.addFile(fullPath, rel + name); |
| 36 | + } else if (stat.isDirectory()) { |
| 37 | + addDirectory(fullPath, `${rel}${name}/`); |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + addDirectory(dir, ''); |
| 43 | + |
| 44 | + zipfile.outputStream.on('error', (err: unknown) => reject(err)); |
| 45 | + zipfile.outputStream.pipe(fs.createWriteStream(output)).on('close', () => { |
| 46 | + resolve(); |
| 47 | + }); |
| 48 | + zipfile.end(); |
| 49 | + }); |
| 50 | + console.log(t('fileGenerated', { file: output })); |
| 51 | +} |
0 commit comments