Created
July 3, 2017 08:52
-
-
Save thekip/dd37942e9fdc243c7b7efdf21c541643 to your computer and use it in GitHub Desktop.
jscodeshift codemod to add angular import statement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = function (file, api) { | |
const j = api.jscodeshift; | |
const ast = j(file.source); | |
const body = ast.find(j.Program).get('body'); | |
// Find each angular.<method>() usage | |
var angularUsages = ast.find(j.MemberExpression, isAngularExpression); | |
if (angularUsages.length === 0) { | |
return null; | |
} | |
// import angular from 'angular' | |
const angularImport = ast.find(j.ImportDeclaration, isAngularImport); | |
if (angularImport.length) { | |
return null; | |
} | |
ast // remove 'use strict' | |
.find(j.ExpressionStatement, isUseStrictExpression) | |
.forEach((ast) => j(ast).remove()); | |
body.get(0).insertBefore(getImport(j)); | |
// Restore opening comments/position | |
body.value[0].comments = body.value[1].comments; | |
delete body.value[1].comments; | |
return ast.toSource({ | |
arrowParensAlways: true, | |
quote: 'single', | |
}); | |
}; | |
function isUseStrictExpression(node) { | |
return ( | |
node.type === 'ExpressionStatement' && | |
node.expression && | |
node.expression.value === 'use strict' | |
); | |
} | |
function isAngularExpression(node) { | |
return ( | |
node.type === 'MemberExpression' && | |
node.object.name === 'angular' | |
); | |
} | |
function isAngularImport(node) { | |
return ( | |
node.type === 'ImportDeclaration' && | |
node.source.value === 'angular' | |
); | |
} | |
function getImport(j) { | |
return j.importDeclaration([j.importDefaultSpecifier(j.identifier('angular'))], j.literal('angular')); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment