@@ -10,38 +10,10 @@ import path from 'node:path';
1010import esbuild from 'esbuild' ;
1111
1212export type BuildOptions = Partial < esbuild . BuildOptions > & {
13- entryPoints : string [ ] | Record < string , string > | { in : string ; out : string } [ ] ;
14- outdir : string ;
13+ readonly entryPoints : esbuild . BuildOptions [ 'entryPoints' ] ;
14+ readonly outdir : string ;
1515} ;
1616
17- /**
18- * Build the source code once using esbuild.
19- */
20- async function build ( options : BuildOptions , didBuild ?: ( outDir : string ) => unknown ) : Promise < void > {
21- await esbuild . build ( {
22- bundle : true ,
23- minify : true ,
24- sourcemap : false ,
25- format : 'esm' ,
26- platform : 'browser' ,
27- target : [ 'es2024' ] ,
28- ...options ,
29- } ) ;
30-
31- await didBuild ?.( options . outdir ) ;
32- }
33-
34- /**
35- * Build the source code once using esbuild, logging errors instead of throwing.
36- */
37- async function tryBuild ( options : BuildOptions , didBuild ?: ( outDir : string ) => unknown ) : Promise < void > {
38- try {
39- await build ( options , didBuild ) ;
40- } catch ( err ) {
41- console . error ( err ) ;
42- }
43- }
44-
4517export async function run (
4618 config : {
4719 srcDir : string ;
@@ -61,6 +33,12 @@ export async function run(
6133 }
6234
6335 const resolvedOptions : BuildOptions = {
36+ bundle : true ,
37+ minify : true ,
38+ sourcemap : false ,
39+ format : 'esm' ,
40+ platform : 'browser' ,
41+ target : [ 'es2024' ] ,
6442 entryPoints : config . entryPoints ,
6543 outdir,
6644 logOverride : {
@@ -71,10 +49,34 @@ export async function run(
7149
7250 const isWatch = args . indexOf ( '--watch' ) >= 0 ;
7351 if ( isWatch ) {
74- await tryBuild ( resolvedOptions , didBuild ) ;
75- const watcher = await import ( '@parcel/watcher' ) ;
76- watcher . subscribe ( config . srcDir , ( ) => tryBuild ( resolvedOptions , didBuild ) ) ;
52+ if ( didBuild ) {
53+ resolvedOptions . plugins = [
54+ ...( resolvedOptions . plugins || [ ] ) ,
55+ {
56+ name : 'did-build' , setup ( pluginBuild ) {
57+ pluginBuild . onEnd ( async result => {
58+ if ( result . errors . length > 0 ) {
59+ return ;
60+ }
61+
62+ try {
63+ await didBuild ( outdir ) ;
64+ } catch ( error ) {
65+ console . error ( 'didBuild failed:' , error ) ;
66+ }
67+ } ) ;
68+ } ,
69+ }
70+ ] ;
71+ }
72+ const ctx = await esbuild . context ( resolvedOptions ) ;
73+ await ctx . watch ( ) ;
7774 } else {
78- return build ( resolvedOptions , didBuild ) . catch ( ( ) => process . exit ( 1 ) ) ;
75+ try {
76+ await esbuild . build ( resolvedOptions ) ;
77+ await didBuild ?.( outdir ) ;
78+ } catch {
79+ process . exit ( 1 ) ;
80+ }
7981 }
8082}
0 commit comments