addExtensions.js 870 B

123456789101112131415161718192021222324252627282930313233
  1. const fs = require('node:fs')
  2. const Path = require('node:path')
  3. module.exports = function (fileInfo, api) {
  4. const j = api.jscodeshift
  5. const root = j(fileInfo.source)
  6. // Add extension to relative path imports
  7. root
  8. .find(j.ImportDeclaration)
  9. .filter(path => path.node.source.value.startsWith('.'))
  10. .forEach(path => {
  11. const importPath = path.node.source.value
  12. const fullPathJs = Path.resolve(
  13. Path.dirname(fileInfo.path),
  14. `${importPath}.js`
  15. )
  16. const fullPathMjs = Path.resolve(
  17. Path.dirname(fileInfo.path),
  18. `${importPath}.mjs`
  19. )
  20. if (fs.existsSync(fullPathJs)) {
  21. path.node.source.value = `${importPath}.js`
  22. } else if (fs.existsSync(fullPathMjs)) {
  23. path.node.source.value = `${importPath}.mjs`
  24. }
  25. })
  26. return root.toSource({
  27. quote: 'single',
  28. })
  29. }