From 4936d2e11a8d0ca3704bfe408548cb26bb3fd5e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=89=E5=92=B2=E6=99=BA=E5=AD=90=20Kevin=20Deng?= Date: Thu, 30 Nov 2023 18:41:21 +0800 Subject: [PATCH] fix(compiler-sfc): throw error when failing to load TS during type resolution (#8883) --- .../compiler-sfc/src/script/resolveType.ts | 27 +++++++++++++++++-- packages/vue/compiler-sfc/register-ts.js | 4 +-- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/packages/compiler-sfc/src/script/resolveType.ts b/packages/compiler-sfc/src/script/resolveType.ts index cf96007beee..d9b4dd1cb8c 100644 --- a/packages/compiler-sfc/src/script/resolveType.ts +++ b/packages/compiler-sfc/src/script/resolveType.ts @@ -719,7 +719,25 @@ let loadTS: (() => typeof TS) | undefined * @private */ export function registerTS(_loadTS: () => typeof TS) { - loadTS = _loadTS + loadTS = () => { + try { + return _loadTS() + } catch (err: any) { + if ( + typeof err.message === 'string' && + err.message.includes('Cannot find module') + ) { + throw new Error( + 'Failed to load TypeScript, which is required for resolving imported types. ' + + 'Please make sure "typescript" is installed as a project dependency.' + ) + } else { + throw new Error( + 'Failed to load TypeScript for resolving imported types.' + ) + } + } + } } type FS = NonNullable @@ -768,7 +786,12 @@ function importSourceToScope( scope: TypeScope, source: string ): TypeScope { - const fs = resolveFS(ctx) + let fs: FS | undefined + try { + fs = resolveFS(ctx) + } catch (err: any) { + return ctx.error(err.message, node, scope) + } if (!fs) { return ctx.error( `No fs option provided to \`compileScript\` in non-Node environment. ` + diff --git a/packages/vue/compiler-sfc/register-ts.js b/packages/vue/compiler-sfc/register-ts.js index 7a073b3a3f8..36de2a350d6 100644 --- a/packages/vue/compiler-sfc/register-ts.js +++ b/packages/vue/compiler-sfc/register-ts.js @@ -1,5 +1,3 @@ if (typeof require !== 'undefined') { - try { - require('@vue/compiler-sfc').registerTS(() => require('typescript')) - } catch (e) {} + require('@vue/compiler-sfc').registerTS(() => require('typescript')) }