blob: 89602798917835d34b151719970b6c12a51c28df [file] [log] [blame]
Mathias Bynens79e2cf02020-05-29 16:46:17 +02001'use strict';
2
3const configurationError = require('./configurationError');
4const globalModules = require('global-modules');
5const resolveFrom = require('resolve-from');
6
7/**
8 * @param {string} basedir
9 * @param {string} lookup
Tim van der Lippe4cb09742022-01-07 14:25:03 +010010 * @param {string} [cwd]
Mathias Bynens79e2cf02020-05-29 16:46:17 +020011 * @return {string}
12 */
Tim van der Lippe4cb09742022-01-07 14:25:03 +010013module.exports = function getModulePath(basedir, lookup, cwd = process.cwd()) {
Mathias Bynens79e2cf02020-05-29 16:46:17 +020014 // 1. Try to resolve from the provided directory
Tim van der Lippe4cb09742022-01-07 14:25:03 +010015 // 2. Try to resolve from `cwd` or `process.cwd()`
Mathias Bynens79e2cf02020-05-29 16:46:17 +020016 // 3. Try to resolve from global `node_modules` directory
17 let path = resolveFrom.silent(basedir, lookup);
18
19 if (!path) {
Tim van der Lippe4cb09742022-01-07 14:25:03 +010020 path = resolveFrom.silent(cwd, lookup);
Mathias Bynens79e2cf02020-05-29 16:46:17 +020021 }
22
23 if (!path) {
24 path = resolveFrom.silent(globalModules, lookup);
25 }
26
27 if (!path) {
28 throw configurationError(`Could not find "${lookup}". Do you need a \`configBasedir\`?`);
29 }
30
31 return path;
32};