如何获取.js/.mjs/.cjs文件中的require或import语句?
如何识别.js、.mjs、.cjs文件中的require/import语句
方法一:静态代码分析脚本(精准识别)
通过JS解析器遍历抽象语法树(AST)是最可靠的方式,能覆盖所有合法的导入/引用场景,包括动态import。以acorn为例:
- 安装依赖:
npm install acorn acorn-walk
- 编写分析脚本(比如
analyze-imports.js):
const fs = require('fs'); const acorn = require('acorn'); const walk = require('acorn-walk'); // 替换为目标文件路径 const targetFile = './example.js'; const code = fs.readFileSync(targetFile, 'utf8'); // 根据文件类型设置sourceType:.mjs用'module',.cjs用'script',.js需参考package.json的type字段 const sourceType = targetFile.endsWith('.mjs') ? 'module' : targetFile.endsWith('.cjs') ? 'script' : 'module'; // 若package.json type为commonjs则改为'script' const ast = acorn.parse(code, { ecmaVersion: 'latest', sourceType }); console.log(`=== ${targetFile} 中的导入/引用语句 ===`); walk.simple(ast, { // 处理静态import语句 ImportDeclaration(node) { console.log(`静态import: ${node.source.value}`); }, // 处理动态import() ImportExpression(node) { if (node.source.type === 'Literal') { console.log(`动态import: ${node.source.value}`); } }, // 处理require调用 CallExpression(node) { if (node.callee.name === 'require' && node.arguments[0]?.type === 'Literal') { console.log(`require: ${node.arguments[0].value}`); } } });
- 运行脚本:
node analyze-imports.js
方法二:命令行文本匹配(快速简单)
如果不需要极致精准,用命令行工具直接匹配关键词即可:
Linux/macOS(grep)
# 匹配所有import语句(含静态和动态) grep -n -E "import.*from|import\(" target-file.js # 匹配require语句 grep -n "require(" target-file.js
-n:显示行号,方便定位
Windows(findstr)
# 匹配import语句 findstr /n "import.*from import(" target-file.js # 匹配require语句 findstr /n "require(" target-file.js
方法三:专用依赖分析工具
用现成工具快速生成依赖列表:
- madge:可以生成可视化依赖图,也能输出文本格式的导入关系
npm install -g madge madge --list target-file.js - depcheck:除了检查未使用的依赖,也会列出文件中用到的导入
npm install -g depcheck depcheck --json | grep -A 10 "target-file.js"
内容的提问来源于stack exchange,提问作者Gary
相关产品推荐
相关产品推荐

