热重载在编译前先检查语法错误,若存在语法错误,输出后直接返回

This commit is contained in:
pqcqaq 2024-11-29 23:58:01 +08:00
parent cf209f37c2
commit 6217b72652
1 changed files with 24 additions and 0 deletions

View File

@ -88,6 +88,7 @@ const restart = async () => {
await shutdown();
}
// 清空lib以下目录的缓存
// 删除所有模块的缓存
Object.keys(require.cache).forEach(function (key) {
if (key.includes('lib')) {
delete require.cache[key];
@ -162,6 +163,7 @@ watcher.on('error', (error) => console.log(`Watcher error: ${error}`));
let isProcessing = false;
const onChangeDebounced = _.debounce(async (path, type) => {
if (isProcessing) {
console.log('Processing, please wait...');
return;
}
isProcessing = true;
@ -175,6 +177,28 @@ const onChangeDebounced = _.debounce(async (path, type) => {
projectReferences,
});
const sourceFile = program.getSourceFile(path);
// 是否有语法错误
const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile);
if (diagnostics.length) {
const syntaxErrors = diagnostics.filter(
(diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error
);
if (syntaxErrors.length) {
console.error(`Error in ${path}`);
syntaxErrors.forEach((diagnostic) => {
console.error(
`${ts.flattenDiagnosticMessageText(
diagnostic.messageText,
'\n'
)}`
);
});
console.error(`文件存在语法错误,请检查修复后重试!`);
isProcessing = false;
return;
}
}
// 只输出单个文件
const emitResult = program.emit(sourceFile);
// 是否成功