|
| 1 | +/* eslint-disable no-console */ |
| 2 | +import fs from 'fs'; |
| 3 | +import { glob } from 'glob'; |
| 4 | +import path from 'path'; |
| 5 | +import { minify_sync } from 'terser'; |
| 6 | + |
| 7 | +interface MinifyOptions { |
| 8 | + verbose: boolean; |
| 9 | + glob: Array<string>; |
| 10 | +} |
| 11 | + |
| 12 | +export function minifyPackage({ verbose, glob: globPatterns }: MinifyOptions) { |
| 13 | + // Find all compiled JavaScript files in dist directories for this package |
| 14 | + // Exclude already minified files (e.g., `*-min.js`) |
| 15 | + const [include, exclude] = [ |
| 16 | + globPatterns.filter(g => !g.startsWith('!')), |
| 17 | + globPatterns.filter(g => g.startsWith('!')).map(g => g.slice(1)), |
| 18 | + ]; |
| 19 | + |
| 20 | + const jsFiles = glob.sync(include, { |
| 21 | + ignore: exclude, |
| 22 | + }); |
| 23 | + |
| 24 | + if (verbose) { |
| 25 | + console.log('Found JavaScript files to minify:', jsFiles); |
| 26 | + } |
| 27 | + |
| 28 | + for (const jsFile of jsFiles) { |
| 29 | + const dir = path.dirname(jsFile); |
| 30 | + const ext = path.extname(jsFile); |
| 31 | + const name = path.basename(jsFile, ext); |
| 32 | + const existingSourceMapFile = path.join(dir, `${name}${ext}.map`); |
| 33 | + const minifiedFile = path.join(dir, `${name}-min${ext}`); |
| 34 | + const minifiedFileMap = path.join(dir, `${name}-min${ext}.map`); |
| 35 | + |
| 36 | + try { |
| 37 | + if (verbose) { |
| 38 | + console.log(`Minifying ${jsFile} -> ${minifiedFile}`); |
| 39 | + } |
| 40 | + |
| 41 | + const fileContent = fs.readFileSync(jsFile, 'utf8'); |
| 42 | + const existingSourceMapContent = fs.readFileSync( |
| 43 | + existingSourceMapFile, |
| 44 | + 'utf8', |
| 45 | + ); |
| 46 | + |
| 47 | + const isEsm = ext === '.mjs' || jsFile.includes('/esm/') || undefined; |
| 48 | + |
| 49 | + const minified = minify_sync(fileContent, { |
| 50 | + sourceMap: { |
| 51 | + filename: path.basename(minifiedFile), |
| 52 | + content: existingSourceMapContent, |
| 53 | + url: path.basename(minifiedFileMap), |
| 54 | + }, |
| 55 | + module: isEsm, |
| 56 | + compress: true, |
| 57 | + mangle: true, |
| 58 | + }); |
| 59 | + |
| 60 | + fs.writeFileSync(minifiedFile, minified.code!); |
| 61 | + fs.writeFileSync(minifiedFileMap, minified.map! as string); |
| 62 | + |
| 63 | + if (verbose) { |
| 64 | + console.log(`✓ Minified ${jsFile}`); |
| 65 | + } |
| 66 | + } catch (error) { |
| 67 | + console.error(`✗ Failed to minify ${jsFile}:`, error); |
| 68 | + throw error; |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + console.log(`✓ Minified ${jsFiles.length} javascript files.`); |
| 73 | +} |
0 commit comments