Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement #1339: use v8-compile-cache to load typescript #1603

Merged
merged 2 commits into from
Jan 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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);
}
}