@@ -2,6 +2,7 @@ import { cyan } from 'ansis';
2
2
import { fork } from 'child_process' ;
3
3
import * as chokidar from 'chokidar' ;
4
4
import { readFileSync } from 'fs' ;
5
+ import { stat } from 'fs/promises' ;
5
6
import * as path from 'path' ;
6
7
import { isAbsolute , join } from 'path' ;
7
8
import * as ts from 'typescript' ;
@@ -168,14 +169,30 @@ export class SwcCompiler extends BaseCompiler {
168
169
swcOptions . jsc . baseUrl = path . join ( rootDir , swcOptions . jsc . baseUrl ) ;
169
170
}
170
171
171
- await swcCli . default ( {
172
+ const swcCliOpts = {
172
173
...options ,
173
174
swcOptions,
174
175
cliOptions : {
175
176
...options . cliOptions ,
176
177
watch : extras . watch ,
177
178
} ,
178
- } ) ;
179
+ } ;
180
+
181
+ if ( extras . watch ) {
182
+ // This is required since SWC no longer supports auto-compiling of newly added files in watch mode.
183
+ // We need to watch the source directory and trigger SWC compilation manually.
184
+ await this . watchFilesInSrcDir ( options , async ( file ) => {
185
+ // Transpile newly added file
186
+ await swcCli . default ( {
187
+ ...swcCliOpts ,
188
+ cliOptions : {
189
+ ...swcCliOpts . cliOptions ,
190
+ filenames : [ file ] ,
191
+ } ,
192
+ } ) ;
193
+ } ) ;
194
+ }
195
+ await swcCli . default ( swcCliOpts ) ;
179
196
}
180
197
181
198
private loadSwcCliBinary ( ) {
@@ -245,6 +262,34 @@ export class SwcCompiler extends BaseCompiler {
245
262
} ;
246
263
}
247
264
265
+ private async watchFilesInSrcDir (
266
+ options : ReturnType < typeof swcDefaultsFactory > ,
267
+ onFileAdded : ( file : string ) => Promise < unknown > ,
268
+ ) {
269
+ const srcDir = options . cliOptions ?. filenames ?. [ 0 ] ;
270
+ const isDirectory = await stat ( srcDir )
271
+ . then ( ( stats ) => stats . isDirectory ( ) )
272
+ . catch ( ( ) => false ) ;
273
+
274
+ if ( ! srcDir || ! isDirectory ) {
275
+ // Skip watching if source directory is not a default "src" folder
276
+ // or any other specified directory
277
+ return ;
278
+ }
279
+ const extensions = options . cliOptions ?. extensions ?? [ 'ts' ] ;
280
+ const watcher = chokidar . watch ( srcDir , {
281
+ ignored : ( file , stats ) =>
282
+ ( stats ?. isFile ( ) &&
283
+ extensions . includes ( path . extname ( file ) . slice ( 1 ) ) ) as boolean ,
284
+ ignoreInitial : true ,
285
+ awaitWriteFinish : {
286
+ stabilityThreshold : 50 ,
287
+ pollInterval : 10 ,
288
+ } ,
289
+ } ) ;
290
+ watcher . on ( 'add' , async ( file ) => onFileAdded ( file ) ) ;
291
+ }
292
+
248
293
private watchFilesInOutDir (
249
294
options : ReturnType < typeof swcDefaultsFactory > ,
250
295
onChange : ( ) => void ,
0 commit comments