function transform(file, { j }, options) { const root = j(file.source); const { identifier } = replaceDefaultImport( 'md5', 'crypto', 'crypto', root, j ); // Replace function calls root .find(j.CallExpression, { callee: { name: identifier } }) .forEach((path) => { const newExpression = j.callExpression( j.memberExpression( j.callExpression( j.memberExpression( j.callExpression( j.memberExpression( j.identifier('crypto'), j.identifier('createHash') ), [j.literal('md5')] ), j.identifier('update') ), path.node.arguments ), j.identifier('digest') ), [j.literal('hex')] ); j(path).replaceWith(newExpression); }); return root.toSource(options); } export function replaceDefaultImport(name, newSpecifier, newName, root, j) { const importDeclaration = root.find(j.ImportDeclaration, { source: { value: name } }); const requireDeclaration = root.find(j.VariableDeclarator, { init: { callee: { name: 'require' }, arguments: [ { value: name } ] } }); const identifier = importDeclaration.paths().length > 0 ? importDeclaration.get().node.specifiers[0].local.name : requireDeclaration.paths().length > 0 ? requireDeclaration.find(j.Identifier).get().node.name : null; importDeclaration.forEach((path) => { j(path).replaceWith( j.importDeclaration( [j.importDefaultSpecifier(j.identifier(newSpecifier))], j.stringLiteral(newName) ) ); }); requireDeclaration.forEach((path) => { const newExpression = j.assignmentExpression( '=', j.identifier(newSpecifier), j.callExpression(j.identifier('require'), [j.literal(newName)]) ); j(path).replaceWith(newExpression); }); return { identifier }; } export default transform;
Input
var md5 = require('md5'); console.log(md5('message')); fs.readFile('example.txt', function(err, buf) { console.log(md5(buf)); });
Output
loading
Read-only