Skip to content

Instantly share code, notes, and snippets.

@maxlath
Created January 7, 2023 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxlath/a8d1c03dfd3ccf3e1e0656ce35a4b62a to your computer and use it in GitHub Desktop.
Save maxlath/a8d1c03dfd3ccf3e1e0656ce35a4b62a to your computer and use it in GitHub Desktop.
Convert `exports defaults { someFunction }` to `export function someFunction {}`
#!/usr/bin/env node
// Convert a modules on the pattern
// export default {
// fnAName: (bla) => {},
// fnBName: (bla) => {},
// }
// to
// export const fnAName = (bla) =>
// export const fnBName = (bla) =>
// How to:
// convert_exports_default_object.js ./file/to/convert.js
const [ file, arg ] = process.argv.slice(2)
if (!file) throw new Error('no file path passed')
const path = require('node:path')
const filePath = path.resolve(process.cwd(), file)
const { readFileSync, writeFileSync } = require('node:fs')
const dry = arg === '--dry' || arg === '-d'
const text = readFileSync(filePath).toString()
const parse = text => {
let inExportedObject = false
const lines = text.split('\n')
return lines
.map((line, i) => {
// console.log('line', i, line, '//' , { inExportedObject })
if (line.startsWith('export default {')) {
inExportedObject = true
return
}
if (inExportedObject && line === '}') {
inExportedObject = false
return
}
if (!inExportedObject) return line
// Drop end of multi-line function comma
if (line === ' },') return '}'
if (line.match(/^\s{2}(\w+):\s+/)) {
return line
.replace(/^\s{2}(\w+):\s+/, 'export const $1 = ')
// Drop end of one-line function comma
.replace(/,$/, '');
}
if (line.match(/^\s{2}(\w+),?$/)) {
return line.replace(/^\s{2}(\w+),?/, 'export const $1 = $1 // FIX ME');
}
// Unindent other lines
if (line.match(/^\s{2}/)) return line.replace(/^\s{2}/, '');
return line
})
.filter(line => line != null)
.join('\n');
}
if (text.includes('export default')) {
if (dry) console.log(parse(text))
else writeFileSync(filePath, parse(text))
} else {
console.log(`doesn't contain export default: ${filePath}`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment