Skip to content

Commit 4079224

Browse files
fix: swc watch new files too
1 parent e343fab commit 4079224

File tree

1 file changed

+47
-2
lines changed

1 file changed

+47
-2
lines changed

lib/compiler/swc/swc-compiler.ts

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { cyan } from 'ansis';
22
import { fork } from 'child_process';
33
import * as chokidar from 'chokidar';
44
import { readFileSync } from 'fs';
5+
import { stat } from 'fs/promises';
56
import * as path from 'path';
67
import { isAbsolute, join } from 'path';
78
import * as ts from 'typescript';
@@ -168,14 +169,30 @@ export class SwcCompiler extends BaseCompiler {
168169
swcOptions.jsc.baseUrl = path.join(rootDir, swcOptions.jsc.baseUrl);
169170
}
170171

171-
await swcCli.default({
172+
const swcCliOpts = {
172173
...options,
173174
swcOptions,
174175
cliOptions: {
175176
...options.cliOptions,
176177
watch: extras.watch,
177178
},
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);
179196
}
180197

181198
private loadSwcCliBinary() {
@@ -245,6 +262,34 @@ export class SwcCompiler extends BaseCompiler {
245262
};
246263
}
247264

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+
248293
private watchFilesInOutDir(
249294
options: ReturnType<typeof swcDefaultsFactory>,
250295
onChange: () => void,

0 commit comments

Comments
 (0)