fixMissingJsImports.mjs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import path from 'node:path'
  2. import fs from 'node:fs'
  3. /**
  4. * @param {import('jscodeshift').FileInfo} file
  5. * @param {import('jscodeshift').API} api
  6. */
  7. module.exports = function transformer(file, api) {
  8. const j = api.jscodeshift
  9. const root = j(file.source)
  10. let hasChanges = false
  11. const considerExtensionReplacement = nodePath => {
  12. const source = nodePath.value.source
  13. if (
  14. !source ||
  15. typeof source.value !== 'string' ||
  16. !source.value.endsWith('.js')
  17. ) {
  18. return
  19. }
  20. const importPath = source.value
  21. const currentDirectory = path.dirname(file.path)
  22. const jsPath = path.resolve(currentDirectory, importPath)
  23. if (fs.existsSync(jsPath)) {
  24. return
  25. }
  26. const mjsImportPath = importPath.replace(/\.js$/, '.mjs')
  27. const mjsPath = path.resolve(currentDirectory, mjsImportPath)
  28. if (fs.existsSync(mjsPath)) {
  29. j(nodePath).get('source').replace(j.literal(mjsImportPath))
  30. hasChanges = true
  31. }
  32. }
  33. const declarationTypes = [
  34. j.ImportDeclaration,
  35. j.ExportNamedDeclaration,
  36. j.ExportAllDeclaration,
  37. ]
  38. declarationTypes.forEach(type => {
  39. root
  40. .find(type, { source: s => s !== null })
  41. .forEach(considerExtensionReplacement)
  42. })
  43. return hasChanges ? root.toSource({ quote: 'single' }) : null
  44. }