imports-visitor
Version:
Babel visitor that makes it easier to work with imports and require calls.
44 lines (42 loc) • 1.45 kB
JavaScript
;
var ImportDefinition = require("./ImportDefinition");
// Gathers all imports and requires and pushes them into the `this.imports`
// array passed via the second argument to traverse.
// Example usage:
// visitor: {
// Program(path) {
// const imports = [];
// path.traverse(importsVisitor, { imports });
// console.log(imports);
// },
// },
var importsVisitor = {
ImportDeclaration: function ImportDeclaration(path, state) {
var _this = this;
var specifiers = path.get("specifiers");
if (specifiers.length === 0) {
this.imports.push(new ImportDefinition(path));
} else {
specifiers.forEach(function (specifier) {
_this.imports.push(new ImportDefinition(specifier));
});
}
},
VariableDeclarator: function VariableDeclarator(path, state) {
var _this2 = this;
if (!(path.get("init").isCallExpression() && path.get("init").get("callee").isIdentifier() && path.get("init").get("callee").node.name === "require")) {
return;
}
if (path.get("id").isObjectPattern()) {
path.get("id").get("properties").forEach(function (property) {
_this2.imports.push(new ImportDefinition(property));
});
} else {
this.imports.push(new ImportDefinition(path));
}
},
"Import|ImportExpression": function ImportImportExpression(path, state) {
this.imports.push(new ImportDefinition(path));
}
};
module.exports = importsVisitor;