Skip to content

Commit

Permalink
Prefer Node's core modules over file modules (#60)
Browse files Browse the repository at this point in the history
This commit makes this resolver behave like Node does [0]:
"Core modules are always preferentially loaded if their identifier is passed to require()"

Additionally this increases performance by avoiding unnecessary disk access. For example webpack calls require("crypto") in a loop.

This commit fixes #56.

[0]: https://nodejs.org/api/modules.html#modules_core_modules
  • Loading branch information
ljani authored and Jontem committed Sep 2, 2018
1 parent 6ab6566 commit 4286b34
Showing 1 changed file with 50 additions and 5 deletions.
55 changes: 50 additions & 5 deletions src/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,47 @@ import { createMatchPath } from "./match-path-sync";
import { configLoader, ExplicitParams } from "./config-loader";
import { options } from "./options";

function getCoreModules(
builtinModules: string[] | undefined
): { [key: string]: boolean } {
builtinModules = builtinModules || [
"assert",
"buffer",
"child_process",
"cluster",
"crypto",
"dgram",
"dns",
"domain",
"events",
"fs",
"http",
"https",
"net",
"os",
"path",
"punycode",
"querystring",
"readline",
"stream",
"string_decoder",
"tls",
"tty",
"url",
"util",
"v8",
"vm",
"zlib"
];

const coreModules: { [key: string]: boolean } = {};
for (let module of builtinModules) {
coreModules[module] = true;
}

return coreModules;
}

/**
* Installs a custom module load function that can adhere to paths in tsconfig.
*/
Expand All @@ -27,13 +68,17 @@ export function register(explicitParams: ExplicitParams): void {
// tslint:disable-next-line:no-require-imports variable-name
const Module = require("module");
const originalResolveFilename = Module._resolveFilename;
const coreModules = getCoreModules(Module.builtinModules);
// tslint:disable-next-line:no-any
Module._resolveFilename = function(request: string, _parent: any): string {
const found = matchPath(request);
if (found) {
const modifiedArguments = [found, ...[].slice.call(arguments, 1)]; // Passes all arguments. Even those that is not specified above.
// tslint:disable-next-line:no-invalid-this
return originalResolveFilename.apply(this, modifiedArguments);
const isCoreModule = coreModules.hasOwnProperty(request);
if (!isCoreModule) {
const found = matchPath(request);
if (found) {
const modifiedArguments = [found, ...[].slice.call(arguments, 1)]; // Passes all arguments. Even those that is not specified above.
// tslint:disable-next-line:no-invalid-this
return originalResolveFilename.apply(this, modifiedArguments);
}
}
// tslint:disable-next-line:no-invalid-this
return originalResolveFilename.apply(this, arguments);
Expand Down

0 comments on commit 4286b34

Please sign in to comment.