Skip to content

Instantly share code, notes, and snippets.

@chrislaughlin
Created May 29, 2019 18:35
Show Gist options
  • Save chrislaughlin/1f931004223ff0ee4b88bb4c2c6f05dd to your computer and use it in GitHub Desktop.
Save chrislaughlin/1f931004223ff0ee4b88bb4c2c6f05dd to your computer and use it in GitHub Desktop.
function findImports (j, ast, pkg) {
return ast.find(j.ImportDeclaration, {
source: {
value: pkg
}
})
}
/**
* Detects CommonJS and import statements for the given package.
* @return true if import were found, else false
*/
function hasRequireOrImport (j, ast, pkg) {
// const requires = findRequires(j, ast, pkg).size()
const imports = findImports(j, ast, pkg).size()
return imports > 0
}
function hasIdentifier (j, ast, name) {
return ast.find(j.Identifier, {
name
}).size() > 0
}
module.exports = function (fileInfo, api) {
const j = api.jscodeshift
const ast = j(fileInfo.source)
if (!hasRequireOrImport(j, ast, 'sinon') && hasIdentifier(j, ast, 'sinon')) {
let imp = ast.find(j.ImportDeclaration, {})
// console.log(imp)
let node = imp.at(imp.size() - 1)
const {statement} = j.template
// const newNode = j.importDeclaration('sinon', 'sinon');
node.insertAfter(statement`import sinon from 'sinon'`)
return node.toSource()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment