diff --git a/package-lock.json b/package-lock.json index bb7dd8c9..6b088bd7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4882,6 +4882,11 @@ "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", "dev": true }, + "v8-compile-cache-lib": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.0.tgz", + "integrity": "sha512-mpSYqfsFvASnSn5qMiwrr4VKfumbPyONLCOPmsR3A6pTY/r0+tSaVbgPWSAIuzbk3lCTa+FForeTiO+wBQGkjA==" + }, "validate-npm-package-license": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", diff --git a/package.json b/package.json index e3e64415..320ee79f 100644 --- a/package.json +++ b/package.json @@ -164,6 +164,7 @@ "create-require": "^1.1.0", "diff": "^4.0.1", "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.0", "yn": "3.1.1" }, "prettier": { diff --git a/src/index.ts b/src/index.ts index 41959f7c..61377508 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,6 +10,7 @@ import type * as _ts from 'typescript'; import type { Transpiler, TranspilerFactory } from './transpilers/types'; import { assign, + attemptRequireWithV8CompileCache, cachedLookup, normalizeSlashes, parse, @@ -568,7 +569,7 @@ export function create(rawOptions: CreateOptions = {}): Service { const compiler = require.resolve(name || 'typescript', { paths: [relativeToPath, __dirname], }); - const ts: typeof _ts = require(compiler); + const ts: typeof _ts = attemptRequireWithV8CompileCache(require, compiler); return { compiler, ts }; } diff --git a/src/util.ts b/src/util.ts index da6cc53b..217dc666 100644 --- a/src/util.ts +++ b/src/util.ts @@ -90,3 +90,26 @@ export function cachedLookup(fn: (arg: T) => R): (arg: T) => R { return cache.get(arg)!; }; } + +/** + * @internal + * Require something with v8-compile-cache, which should make subsequent requires faster. + * Do lots of error-handling so that, worst case, we require without the cache, and users are not blocked. + */ +export function attemptRequireWithV8CompileCache( + requireFn: typeof require, + specifier: string +) { + try { + const v8CC = ( + require('v8-compile-cache-lib') as typeof import('v8-compile-cache-lib') + ).install(); + try { + return requireFn(specifier); + } finally { + v8CC?.uninstall(); + } + } catch (e) { + return requireFn(specifier); + } +}