@@ -5,18 +5,13 @@ import { init, parse } from 'es-module-lexer';
55
66import {
77 isBareModuleSpecifier ,
8- splitPath ,
9- traverseUp
108} from './utils.js' ;
119
12- const require = createRequire ( import . meta. url ) ;
13-
1410/**
1511 *
1612 * @param {string[] } paths
1713 * @param {{
1814 * nodeModulesDepth?: number,
19- * basePath?: string,
2015 * }} options
2116 * @returns {Promise<string[]> }
2217 */
@@ -25,25 +20,21 @@ export async function findDependencies(paths, options = {}) {
2520 const dependencies = new Set ( ) ;
2621
2722 const nodeModulesDepth = options ?. nodeModulesDepth ?? 3 ;
28- const basePath = options ?. basePath ?? process . cwd ( ) ;
2923
3024 /** Init es-module-lexer wasm */
3125 await init ;
3226
33- paths . forEach ( path => {
34- const source = fs . readFileSync ( path ) . toString ( ) ;
27+ paths . forEach ( filePath => {
28+ const source = fs . readFileSync ( filePath ) . toString ( ) ;
3529 const [ imports ] = parse ( source ) ;
3630
31+ const pathRequire = createRequire ( path . resolve ( filePath ) ) ;
32+
3733 imports ?. forEach ( i => {
3834 /** Skip built-in modules like fs, path, etc */
3935 if ( builtinModules . includes ( i . n ) ) return ;
4036 try {
41- const pathToDependency = require . resolve ( i . n , { paths : [
42- /** Current project's node_modules */
43- basePath ,
44- /** Monorepo, look upwards in filetree n times */
45- ...traverseUp ( nodeModulesDepth )
46- ] } ) ;
37+ const pathToDependency = pathRequire . resolve ( i . n ) ;
4738
4839 importsToScan . add ( pathToDependency ) ;
4940 dependencies . add ( pathToDependency ) ;
@@ -60,24 +51,18 @@ export async function findDependencies(paths, options = {}) {
6051 const source = fs . readFileSync ( dep ) . toString ( ) ;
6152 const [ imports ] = parse ( source ) ;
6253
54+ const depRequire = createRequire ( dep ) ;
55+
6356 imports ?. forEach ( i => {
6457 /** Skip built-in modules like fs, path, etc */
6558 if ( builtinModules . includes ( i . n ) ) return ;
66- const { packageRoot } = splitPath ( dep ) ;
6759 const fileToFind = isBareModuleSpecifier ( i . n ) ? i . n : path . join ( path . dirname ( dep ) , i . n ) ;
6860 try {
6961 /**
7062 * First check in the dependencies' node_modules, then in the project's node_modules,
7163 * then up, and up, and up
7264 */
73- const pathToDependency = require . resolve ( fileToFind , { paths : [
74- /** Nested node_modules */
75- packageRoot ,
76- /** Current project's node_modules */
77- basePath ,
78- /** Monorepo, look upwards in filetree n times */
79- ...traverseUp ( nodeModulesDepth )
80- ] } ) ;
65+ const pathToDependency = depRequire . resolve ( fileToFind ) ;
8166 /**
8267 * Don't add dependencies we've already scanned, also avoids circular dependencies
8368 * and multiple modules importing from the same module
@@ -94,4 +79,4 @@ export async function findDependencies(paths, options = {}) {
9479 }
9580
9681 return [ ...dependencies ] ;
97- }
82+ }
0 commit comments