我正在开发一个开发工具,它可以为我提供一些代码指标。
我希望该工具能够遍历源文件并计算每个导入值和每个库的使用情况 (#loc)。
即对于lodash,我想知道 isEqual
的用法, cloneDeep
。
我想要作为输出:
+------------+------------+---------+
| Library | Imported | #LOC |
+------------+------------+---------+
| Lodash | isEqual | 20|
| Lodash | cloneDeep | 4|
+------------+------------+---------+
该工具应找到的内容的示例文件
1 // aFile.js
2 import {isEqual, cloneDeep} from 'lodash'
3 // some code ..
4 if (isEqual(variableA, variableB)) {
5 // ^^^^^^^
6 }
7 let myClonedObject = cloneDeep(myObject);
8 // ^^^^^^^^^
我开始以 babel 插件的形式实现,因为我知道它会让我轻松
- 以可读格式 (AST) 解析代码
- 访问所有 importDeclaration
- 获取相关引用资料
- 计算用量
当前实现
export default function({ types: t }) {
return {
visitor: {
ImportDeclaration(path, state) {
if(path.get('source').node.value === 'lodash') {
path.get('specifiers').forEach(function(specifier) {
if(specifier.node.imported) {
const importedIdentifierName = specifier.node.imported.name;
if(importedIdentifierName === 'isEqual') {
const isEqualLoc = new Set();
const {referencePaths} = path.scope.getBinding(importedIdentifierName);
referencePaths.forEach(function(referencePath) {
isEqualLOC.add(referencePath.node.loc.start.line);
});
console.log(isEqualLOC.size);
}
}
});
}
}
}
};
};
对于这个工具,我只对代码进行读取操作(不进行转换/生成)。
我的问题:如何将 babel 插件(lib/import/#loc)中生成的信息共享到 babel-cli
的结果命令或任何其他 API?
我考虑用 console.log
记录结果(具有特定的 id)但在我看来,这似乎是一种解决方法。
我想知道是否有一些明确的 API 可以从 babel 插件中公开信息。
最佳答案
这似乎是使用 Babel 的实用程序构建的更好,但在您自己的基础上实现。 Babel 目前不提供任何输出统计数据或任何内容的方法。例如,您可以将插件更改为类似的脚本
const fs = require('fs');
const babylon = require('bablylon');
const traverse = require('babel-traverse');
const data = fs.readFileSync('./thing.js');
traverse(babylon.parse(data), {
ImportDeclaration(path) {
// ...
},
});
// Do whatever output you want here
关于javascript - Babel 插件 - 静态代码分析后获取结构化信息作为输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42332401/