babel-plugin-transform-modules-ui5
Version:
An unofficial babel plugin for SAP UI5.
37 lines (34 loc) • 1.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getImportDeclaration = getImportDeclaration;
exports.saveImports = void 0;
var _core = require("@babel/core");
let importDeclarations = {};
const saveImports = file => {
// save all import declarations before "unneeded" ones are removed by the TypeScript plugin
importDeclarations[file.opts.filename] = file.ast.program.body.filter(_core.types.isImportDeclaration); // right now even the removed import still exists later and can be re-added. Otherwise do: .map(decl => t.cloneNode(decl));
};
// can be called from visitor to access previously present declarations
exports.saveImports = saveImports;
function getImportDeclaration(filename, typeName) {
if (!filename || !typeName) {
return null;
}
const typeNameParts = typeName.split(".");
// find the declaration importing the typeName among the collected import declarations in this file
const filteredDeclarations = importDeclarations[filename].filter(importDeclaration => {
// each import declaration can import several entities, so let's check all of them
for (let specifier of importDeclaration.specifiers) {
if ((_core.types.isImportDefaultSpecifier(specifier) || _core.types.isImportNamespaceSpecifier(specifier)) && specifier.local.name === typeNameParts[0]) {
// if the import is default, then the typeName should only have one part (the import name)
return true;
} else if (_core.types.isImportSpecifier(specifier) && specifier.imported.name === typeNameParts[typeNameParts.length - 1]) {
// If the import is named, then the last part of the typeName should match the imported name
return true;
}
}
});
return filteredDeclarations[0]; // should be exactly one
}