Skip to content

Commit 8949654

Browse files
authored
Implement #1339: use v8-compile-cache to load typescript (#1603)
* initial commit * lint-fix
1 parent 89f88eb commit 8949654

File tree

4 files changed

+31
-1
lines changed

4 files changed

+31
-1
lines changed

package-lock.json

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,7 @@
164164
"create-require": "^1.1.0",
165165
"diff": "^4.0.1",
166166
"make-error": "^1.1.1",
167+
"v8-compile-cache-lib": "^3.0.0",
167168
"yn": "3.1.1"
168169
},
169170
"prettier": {

src/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import type * as _ts from 'typescript';
1010
import type { Transpiler, TranspilerFactory } from './transpilers/types';
1111
import {
1212
assign,
13+
attemptRequireWithV8CompileCache,
1314
cachedLookup,
1415
normalizeSlashes,
1516
parse,
@@ -568,7 +569,7 @@ export function create(rawOptions: CreateOptions = {}): Service {
568569
const compiler = require.resolve(name || 'typescript', {
569570
paths: [relativeToPath, __dirname],
570571
});
571-
const ts: typeof _ts = require(compiler);
572+
const ts: typeof _ts = attemptRequireWithV8CompileCache(require, compiler);
572573
return { compiler, ts };
573574
}
574575

src/util.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,3 +90,26 @@ export function cachedLookup<T, R>(fn: (arg: T) => R): (arg: T) => R {
9090
return cache.get(arg)!;
9191
};
9292
}
93+
94+
/**
95+
* @internal
96+
* Require something with v8-compile-cache, which should make subsequent requires faster.
97+
* Do lots of error-handling so that, worst case, we require without the cache, and users are not blocked.
98+
*/
99+
export function attemptRequireWithV8CompileCache(
100+
requireFn: typeof require,
101+
specifier: string
102+
) {
103+
try {
104+
const v8CC = (
105+
require('v8-compile-cache-lib') as typeof import('v8-compile-cache-lib')
106+
).install();
107+
try {
108+
return requireFn(specifier);
109+
} finally {
110+
v8CC?.uninstall();
111+
}
112+
} catch (e) {
113+
return requireFn(specifier);
114+
}
115+
}

0 commit comments

Comments
 (0)