Skip to content

Commit

Permalink
Fixes #147—Ensures core modules beat shadowed ones
Browse files Browse the repository at this point in the history
Given 'util' as an example native module which is also installed as an
npm package, then in order for browserify/resolve to act consistently
with native `require.resolve`, these should be true:

```
resolve.sync('util') // returns 'util'
resolve.sync('util/') // returns 'node_modules/util/index.js'
```
  • Loading branch information
searls committed Mar 23, 2018
1 parent 9978c5a commit 668df11
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
11 changes: 7 additions & 4 deletions lib/async.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,13 @@ module.exports = function resolve(x, options, callback) {
loadAsDirectory(res, opts.package, onfile);
} else loadAsFile(res, opts.package, onfile);
} else loadNodeModules(x, y, function (err, n, pkg) {
if (err) cb(err);
else if (n) cb(null, n, pkg);
else if (core[x]) return cb(null, x);
else {
if (err) {
cb(err);
} else if (core[x]) {
cb(null, x);
} else if (n) {
cb(null, n, pkg);
} else {
var moduleError = new Error("Cannot find module '" + x + "' from '" + y + "'");
moduleError.code = 'MODULE_NOT_FOUND';
cb(moduleError);
Expand Down
4 changes: 2 additions & 2 deletions lib/sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@ module.exports = function (x, options) {
if (x === '..' || x.slice(-1) === '/') res += '/';
var m = loadAsFileSync(res) || loadAsDirectorySync(res);
if (m) return m;
} else if (core[x]) {
return x;
} else {
var n = loadNodeModulesSync(x, y);
if (n) return n;
}

if (core[x]) return x;

var err = new Error("Cannot find module '" + x + "' from '" + y + "'");
err.code = 'MODULE_NOT_FOUND';
throw err;
Expand Down
17 changes: 17 additions & 0 deletions test/shadowed_core.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@ test('shadowed core modules still return core module', function (t) {
});
});

test('shadowed core modules still return core module [sync]', function (t) {
t.plan(1);

var res = resolve.sync('util', { basedir: path.join(__dirname, 'shadowed_core') });

t.equal(res, 'util');
});

test('shadowed core modules return shadow when appending `/`', function (t) {
t.plan(2);

Expand All @@ -19,3 +27,12 @@ test('shadowed core modules return shadow when appending `/`', function (t) {
t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js'));
});
});

test('shadowed core modules return shadow when appending `/` [sync]', function (t) {
t.plan(1);

var res = resolve.sync('util/', { basedir: path.join(__dirname, 'shadowed_core') });

t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js'));
});

0 comments on commit 668df11

Please sign in to comment.