function transform(file, { j }) { const ast = j(file.source); // Find the import specifier for left-pad in case of aliases const leftPadImports = ast.find(j.ImportDeclaration, { source: { value: "left-pad" }, }); // Get import specifier name const leftPadLocalName = getSpecifierName( leftPadImports.find(j.ImportDefaultSpecifier) ); leftPadImports.remove(); // Replace all usage of the leftPadLocalName with native padStart ast .find(j.CallExpression, { callee: { name: leftPadLocalName } }) .forEach((callPath) => { const args = callPath.node.arguments; if (args.length >= 2) { const stringArg = args[0]; const targetLength = args[1]; const padString = args.length > 2 ? args[2] : j.literal(" "); // Replace with the padStart call j(callPath).replaceWith( j.callExpression( j.memberExpression(stringArg, j.identifier("padStart")), [targetLength, padString] ) ); } }); return ast.toSource(); } export default transform; function getSpecifierName(specifiers) { if (!specifiers.length) return null; return specifiers.nodes()[0].local.name; }
Input
import leftpad from 'left-pad'; const result = leftpad('hello', 10); console.log(leftpad('world', 15, '*')); foo = 'bar'; const padded = leftpad(foo, 8);
Output
loading
Read-only