cjs-to-esm.mjs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import minimist from 'minimist'
  2. import { exec } from 'node:child_process'
  3. import { promisify } from 'node:util'
  4. import Runner from 'jscodeshift/src/Runner.js'
  5. import { fileURLToPath } from 'node:url'
  6. import path from 'node:path'
  7. const __dirname = fileURLToPath(new URL('.', import.meta.url))
  8. // use minimist to get a list of files from the argv
  9. const argv = minimist(process.argv.slice(2), {
  10. boolean: ['usage'],
  11. })
  12. function printUsage() {
  13. console.log(
  14. 'node scripts/esm-migration/cjs-to-esm.mjs [files] [--format] [--lint] [--usage]'
  15. )
  16. console.log(
  17. 'WARNING: this will only work in local development as important dependencies will be missing in production'
  18. )
  19. console.log('Options:')
  20. console.log(' files: a list of files to convert')
  21. console.log('--format: run prettier to fix formatting')
  22. console.log(' --lint: run eslint to fix linting')
  23. console.log(' --usage: show this help message')
  24. process.exit(0)
  25. }
  26. const files = argv._
  27. if (argv.usage) {
  28. printUsage()
  29. }
  30. if (!Array.isArray(files) || files.length === 0) {
  31. console.error('You must provide a list of files to convert')
  32. printUsage()
  33. process.exit(1)
  34. }
  35. const promisifiedExec = promisify(exec)
  36. const cjsTransform = fileURLToPath(
  37. import.meta.resolve('5to6-codemod/transforms/cjs.js')
  38. )
  39. const exportsTransform = fileURLToPath(
  40. import.meta.resolve('5to6-codemod/transforms/exports.js')
  41. )
  42. const overleafTransform = fileURLToPath(
  43. import.meta.resolve('./overleaf-es-codemod.js')
  44. )
  45. const config = {
  46. output: __dirname,
  47. silent: true,
  48. print: false,
  49. verbose: 0,
  50. hoist: true,
  51. }
  52. await Runner.run(cjsTransform, files, config)
  53. await Runner.run(exportsTransform, files, config)
  54. await Runner.run(overleafTransform, files, config)
  55. const webRoot = fileURLToPath(new URL('../../', import.meta.url))
  56. for (const file of files) {
  57. // move files with git mv
  58. await promisifiedExec(`git mv ${file} ${file.replace('.js', '.mjs')}`)
  59. const relativePath = path.relative(webRoot, file)
  60. console.log(
  61. `transformed ${relativePath} and renamed it to have a .mjs extension`
  62. )
  63. }