Skip to content

Commit

Permalink
fix(compiler-sfc): throw error when failing to load TS during type re…
Browse files Browse the repository at this point in the history
…solution (#8883)
  • Loading branch information
sxzz authored Nov 30, 2023
1 parent 5199a12 commit 4936d2e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
27 changes: 25 additions & 2 deletions packages/compiler-sfc/src/script/resolveType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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']>
Expand Down Expand Up @@ -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. ` +
Expand Down
4 changes: 1 addition & 3 deletions packages/vue/compiler-sfc/register-ts.js
Original file line number Diff line number Diff line change
@@ -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'))
}

0 comments on commit 4936d2e

Please sign in to comment.