|
1 | | -import { build as _build, analyzeMetafile, BuildOptions } from 'esbuild' |
| 1 | +import { build as _build, analyzeMetafile, BuildOptions, WatchMode } from 'esbuild' |
| 2 | +import { mapEntries, writeDefinition } from './definitions' |
2 | 3 |
|
3 | | -const watch = process.argv.includes('--watch') || process.argv.includes('-w') |
| 4 | +/** Watch mode handler for adding actions on rebuild. */ |
| 5 | +const handleRebuild: WatchMode['onRebuild'] = async (error, result) => { |
| 6 | + if (error) { |
| 7 | + console.error('👀❎ Watch build failed:', error) |
| 8 | + } else { |
| 9 | + const meta = await analyzeMetafile(result!.metafile!) |
| 10 | + console.log('👀✅ Watch build succeeded', meta) |
| 11 | + } |
| 12 | +} |
4 | 13 |
|
5 | | -/** Build project with Esbuild. */ |
6 | | -export const build = async (opts: BuildOptions = {}) => |
7 | | - _build({ |
8 | | - watch: watch |
9 | | - ? { |
10 | | - onRebuild: (error, result) => error |
11 | | - ? console.error('👀❎ Watch build failed:', error) |
12 | | - : analyzeMetafile(result!.metafile!).then( |
13 | | - (meta) => console.log('👀✅ Watch build succeeded', meta) |
14 | | - ) |
15 | | - } |
16 | | - : false, |
17 | | - ...opts |
18 | | - }) |
| 14 | +/** Build project with ES Build, adds reload handler in watch mode. */ |
| 15 | +export const build = async (options: BuildOptions = {}) => { |
| 16 | + const entries = mapEntries(options) |
| 17 | + const writeDefinitions = () => Promise.all(entries.map(writeDefinition)) |
| 18 | + const watchEnabled = |
| 19 | + options.watch || |
| 20 | + process.argv.includes('--watch') || |
| 21 | + process.argv.includes('-w') |
| 22 | + const watch: BuildOptions['watch'] = { |
| 23 | + onRebuild: async (error, result) => { |
| 24 | + await writeDefinitions() |
| 25 | + return handleRebuild(error, result) |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + return _build({...options, watch: watchEnabled ? watch : undefined }) |
19 | 30 | .then(({ metafile }) => analyzeMetafile(metafile!)) |
20 | 31 | .then(console.log) |
| 32 | + .then(writeDefinitions) |
21 | 33 | .catch(_ => process.exit(1)) |
| 34 | +} |
0 commit comments