injectImports.js 956 B

1234567891011121314151617181920212223242526272829
  1. module.exports = function injectImports (fileInfo, api, { imports }) {
  2. const j = api.jscodeshift
  3. const root = j(fileInfo.source)
  4. const toImportAST = i => j(`${i}\n`).nodes()[0].program.body[0]
  5. const toImportHash = node => JSON.stringify({
  6. specifiers: node.specifiers.map(s => s.local.name),
  7. source: node.source.raw
  8. })
  9. const declarations = root.find(j.ImportDeclaration)
  10. const importSet = new Set(declarations.nodes().map(toImportHash))
  11. const nonDuplicates = node => !importSet.has(toImportHash(node))
  12. const importASTNodes = imports.map(toImportAST).filter(nonDuplicates)
  13. if (declarations.length) {
  14. declarations
  15. .at(-1)
  16. // a tricky way to avoid blank line after the previous import
  17. .forEach(({ node }) => delete node.loc)
  18. .insertAfter(importASTNodes)
  19. } else {
  20. // no pre-existing import declarations
  21. root.get().node.program.body.unshift(...importASTNodes)
  22. }
  23. return root.toSource()
  24. }