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

refactor: use core Node.js resolve function if possible #25

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,26 @@

const path = require('path')
const Module = require('module')
const resolve = require('resolve')
const debug = require('debug')('require-in-the-middle')
const parse = require('module-details-from-path')

module.exports = Hook

// Feature detection: This property was added in Node.js 8.9.0, the same time
// as the `paths` options argument was added to the `require.resovle` function,
// which is the one we want
let resolve
if (require.resolve.paths) {
resolve = function (moduleName, basedir) {
return require.resolve(moduleName, { paths: [basedir] })
}
} else {
const _resolve = require('resolve')
resolve = function (moduleName, basedir) {
return _resolve.sync(moduleName, { basedir })
}
}

// 'foo/bar.js' or 'foo/bar/index.js' => 'foo/bar'
const normalize = /([/\\]index)?(\.js)?$/

Expand Down Expand Up @@ -110,7 +124,7 @@ function Hook (modules, options, onrequire) {
// figure out if this is the main module file, or a file inside the module
let res
try {
res = resolve.sync(moduleName, { basedir: basedir })
res = resolve(moduleName, basedir)
} catch (e) {
debug('could not resolve module: %s', moduleName)
return exports // abort if module could not be resolved (e.g. no main in package.json and no index.js file)
Expand Down