|
| 1 | +import chalk from "chalk"; |
| 2 | +import { analyzeMetafile, build } from "esbuild"; |
| 3 | +import { readFile } from "fs/promises"; |
| 4 | +import path from "path"; |
| 5 | +import { fileURLToPath } from "url"; |
| 6 | + |
| 7 | +const nodeTarget = "node16"; |
| 8 | + |
| 9 | +const __dirname = path.dirname(fileURLToPath(import.meta.url)); |
| 10 | +const packageJsonPath = path.resolve(__dirname, "package.json"); |
| 11 | + |
| 12 | +async function getExternals() { |
| 13 | + const packageJson = JSON.parse(await readFile(packageJsonPath)); |
| 14 | + |
| 15 | + return Object.keys(packageJson.peerDependencies); |
| 16 | +} |
| 17 | + |
| 18 | +async function bundle(externalDeps, format, outDir) { |
| 19 | + return build({ |
| 20 | + entryPoints: ["./src/index.ts"], |
| 21 | + outfile: `${outDir}/index.js`, |
| 22 | + metafile: true, |
| 23 | + bundle: true, |
| 24 | + format: format, |
| 25 | + external: externalDeps, |
| 26 | + platform: "node", |
| 27 | + target: nodeTarget, |
| 28 | + treeShaking: true, |
| 29 | + }); |
| 30 | +} |
| 31 | + |
| 32 | +(async () => { |
| 33 | + try { |
| 34 | + const startTime = Date.now(); |
| 35 | + console.info( |
| 36 | + chalk.bold( |
| 37 | + `🚀 ${chalk.blueBright("rollup-plugin-conditional-exec")} Build\n` |
| 38 | + ) |
| 39 | + ); |
| 40 | + |
| 41 | + const externalDeps = await getExternals(); |
| 42 | + |
| 43 | + for (const [format, outDir] of [ |
| 44 | + ["cjs", "dist/cjs"], |
| 45 | + ["esm", "dist/esm"], |
| 46 | + ]) { |
| 47 | + console.info(chalk.bold(`⚙️ Bundling: ${chalk.greenBright(format)}\n`)); |
| 48 | + const result = await bundle(externalDeps, format, outDir); |
| 49 | + |
| 50 | + const analysis = await analyzeMetafile(result.metafile); |
| 51 | + console.info(`📝 Bundle Analysis:${analysis}`); |
| 52 | + |
| 53 | + console.info( |
| 54 | + chalk.bold(chalk.greenBright(`✔ Bundling ${format} completed!\n`)) |
| 55 | + ); |
| 56 | + } |
| 57 | + |
| 58 | + console.info( |
| 59 | + `${chalk.bold.green("✔ Bundled package successfully!")} (${ |
| 60 | + Date.now() - startTime |
| 61 | + }ms)` |
| 62 | + ); |
| 63 | + } catch (error) { |
| 64 | + console.error(`🧨 ${chalk.red.bold("Failed:")} ${error.message}`); |
| 65 | + console.debug(`📚 ${chalk.blueBright.bold("Stack:")} ${error.stack}`); |
| 66 | + process.exit(1); |
| 67 | + } |
| 68 | +})(); |
0 commit comments