]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
fix(compiler-sfc): throw error when failing to load TS during type resolution (#8883)
author三咲智子 Kevin Deng <sxzz@sxzz.moe>
Thu, 30 Nov 2023 10:41:21 +0000 (18:41 +0800)
committerGitHub <noreply@github.com>
Thu, 30 Nov 2023 10:41:21 +0000 (18:41 +0800)
packages/compiler-sfc/src/script/resolveType.ts
packages/vue/compiler-sfc/register-ts.js

index cf96007beee4ce4b9a573bccd03be4be0ccd6bc9..d9b4dd1cb8c78dc500bc8fa7aef946a51a1ef881 100644 (file)
@@ -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<SFCScriptCompileOptions['fs']>
@@ -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. ` +
index 7a073b3a3f8732ee20ffacccedd972fb8230d851..36de2a350d6ec7a5297482f5a6e870613b0d4f30 100644 (file)
@@ -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'))
 }