如何找出项目中最常被引用的非npm模块JS文件?
Hey there! Finding the most referenced internal JS files in a project with lots of interdependencies is a common task—here are a few solid ways to do it, focusing on require and import statements:
Method 1: Custom Node.js Script
This is the most flexible option, since you can tweak the matching logic to fit your project's syntax (CommonJS, ES Modules, JSX, etc.). Save this as count-references.js in your project root:
const fs = require('fs').promises; const path = require('path'); // Exclude directories you don't want to scan (adjust as needed) const EXCLUDE_DIRS = ['node_modules', 'dist', 'build']; // Regex to match both require() and import statements const IMPORT_REGEX = /(?:require\(['"](.*?)['"]\)|import.*from\s*['"](.*?)['"])/g; async function scanDirectory(dir) { const stats = await fs.stat(dir); if (!stats.isDirectory()) return {}; const files = await fs.readdir(dir); const referenceCounts = {}; for (const file of files) { const fullPath = path.join(dir, file); const fileStats = await fs.stat(fullPath); if (fileStats.isDirectory()) { if (!EXCLUDE_DIRS.includes(file)) { const subDirCounts = await scanDirectory(fullPath); // Merge subdirectory results Object.entries(subDirCounts).forEach(([path, count]) => { referenceCounts[path] = (referenceCounts[path] || 0) + count; }); } continue; } // Skip non-JS/JSX files (add .ts/.tsx if using TypeScript) const ext = path.extname(file); if (!['.js', '.jsx'].includes(ext)) continue; const content = await fs.readFile(fullPath, 'utf8'); let match; while ((match = IMPORT_REGEX.exec(content)) !== null) { const importedPath = match[1] || match[2]; // Skip npm packages (target relative/project paths only) if (!importedPath || importedPath.startsWith('@') || importedPath.match(/^[a-z-]+$/)) continue; // Resolve relative paths to absolute project paths let resolvedPath = importedPath.startsWith('.') ? path.resolve(path.dirname(fullPath), importedPath) : path.resolve(process.cwd(), importedPath); // Handle cases where extensions are omitted if (!await fs.exists(resolvedPath)) { resolvedPath += '.js'; if (!await fs.exists(resolvedPath)) resolvedPath += 'x'; } if (await fs.exists(resolvedPath)) { const projectRelativePath = path.relative(process.cwd(), resolvedPath); referenceCounts[projectRelativePath] = (referenceCounts[projectRelativePath] || 0) + 1; } } } return referenceCounts; } // Run the script (async () => { const counts = await scanDirectory(process.cwd()); // Sort results by reference count (highest first) const sorted = Object.entries(counts).sort((a, b) => b[1] - a[1]); console.log('Most referenced non-npm JS files:'); sorted.forEach(([filePath, count]) => { console.log(`${count} references: ${filePath}`); }); })();
To use it:
- Run
node count-references.jsin your project root - Adjust
EXCLUDE_DIRSand file extensions if your project uses TypeScript or other variants
Method 2: Use Existing Tools
If you don't want to write custom code, these tools do the heavy lifting:
- dependency-cruiser: Install it via
npm install -g dependency-cruiser, then run:
This outputs sorted results of internal file references.depcruise src --include-only "^src" --output-type json | jq '.modules | sort_by(.dependents.length) | reverse | .[] | "\(.dependents.length) references: \(.source)"' - madge: A dependency graph tool that also counts references. Install with
npm install -g madge, then run:
It will print each file's reference count in descending order.madge --count src
Method 3: IDE Global Search (Small Projects)
For smaller projects, your IDE's search works great:
- In VS Code, open global search (
Ctrl+Shift+F) and use the regexrequire\(['"](.*?)['"]\)|import.*from\s*['"](.*?)['"] - For each non-npm path in the results, check the file-specific match count on the right side of the search panel to tally references.
内容的提问来源于stack exchange,提问作者Gunther
相关产品推荐
相关产品推荐

