Skip to content

Commit

Permalink
Implement #1339: use v8-compile-cache to load typescript (#1603)
Browse files Browse the repository at this point in the history
* initial commit

* lint-fix
  • Loading branch information
cspotcode authored Jan 21, 2022
1 parent 89f88eb commit 8949654
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 1 deletion.
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type * as _ts from 'typescript';
import type { Transpiler, TranspilerFactory } from './transpilers/types';
import {
assign,
attemptRequireWithV8CompileCache,
cachedLookup,
normalizeSlashes,
parse,
Expand Down Expand Up @@ -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 };
}

Expand Down
23 changes: 23 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,26 @@ export function cachedLookup<T, R>(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);
}
}

0 comments on commit 8949654

Please sign in to comment.