Skip to content

Commit

Permalink
Expose require.resolve.paths()
Browse files Browse the repository at this point in the history
  • Loading branch information
zertosh committed May 10, 2019
1 parent ad9f842 commit 0daa6be
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 2 deletions.
1 change: 1 addition & 0 deletions test/fixtures/require-resolve-paths.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log('%j', require.resolve.paths(process.argv[2]));
51 changes: 51 additions & 0 deletions test/module-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
'use strict';

const tap = require('tap');
const child_process = require('child_process');
const path = require('path');

tap.beforeEach(cb => {
delete process.env.DISABLE_V8_COMPILE_CACHE;
cb();
});

tap.test('require.resolve.paths module', t => {
const ps = child_process.spawnSync(
process.execPath,
[
'--require',
'..',
require.resolve('./fixtures/require-resolve-paths'),
'tap',
],
{cwd: __dirname}
);

const expected = [path.resolve(__dirname, 'fixtures', 'node_modules')]
.concat(require.resolve.paths('tap'));

t.same(JSON.parse(ps.stdout), expected);
t.equal(ps.stderr.toString(), '');
t.equal(ps.status, 0);

t.end();
});

tap.test('require.resolve.paths relative', t => {
const ps = child_process.spawnSync(
process.execPath,
[
'--require',
'..',
require.resolve('./fixtures/require-resolve-paths'),
'./foo',
],
{cwd: __dirname}
);

t.same(JSON.parse(ps.stdout), [path.resolve(__dirname, 'fixtures')]);
t.equal(ps.stderr.toString(), '');
t.equal(ps.status, 0);

t.end();
});
15 changes: 13 additions & 2 deletions v8-compile-cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,12 +155,23 @@ class NativeCompileCache {
this._previousModuleCompile = Module.prototype._compile;
Module.prototype._compile = function(content, filename) {
const mod = this;

function require(id) {
return mod.require(id);
}
require.resolve = function(request, options) {

// https://github.com/nodejs/node/blob/v10.15.3/lib/internal/modules/cjs/helpers.js#L28
function resolve(request, options) {
return Module._resolveFilename(request, mod, false, options);
};
}
require.resolve = resolve;

// https://github.com/nodejs/node/blob/v10.15.3/lib/internal/modules/cjs/helpers.js#L37
function paths(request) {
return Module._resolveLookupPaths(request, mod, true);
}
resolve.paths = paths;

require.main = process.mainModule;

// Enable support to add extra extension types
Expand Down

0 comments on commit 0daa6be

Please sign in to comment.