Skip to content

Instantly share code, notes, and snippets.

@danielkv
Last active November 30, 2022 17:24
Show Gist options
  • Save danielkv/c040f948ecd03e128b919ee597920ace to your computer and use it in GitHub Desktop.
Save danielkv/c040f948ecd03e128b919ee597920ace to your computer and use it in GitHub Desktop.
const path = require('path')
const fs = require('fs')
const { format } = require('prettier')
const folder = path.resolve(__dirname)
const outputFile = path.resolve(__dirname, 'index.ts')
function generateExport(name, findings) {
let exportString = 'export {'
findings.forEach((finding, index) => {
if (index > 0) exportString += ','
exportString += `\n ${finding.component}`
})
exportString += `\n} from './${name}'`
return exportString
}
fs.readdir(folder, (err, files) => {
if (err) return
const exports = []
files.forEach((file) => {
const dirPath = `${folder}/${file}`
if (!fs.statSync(dirPath).isDirectory()) return
const filePath = `${dirPath}/index.tsx`
if (!fs.existsSync(dirPath) || !fs.statSync(filePath).isFile()) return
const content = fs.readFileSync(filePath, 'utf-8')
const exportRegExp =
/export[\s]+(type|const|default|function)[\s]+([a-zA-Z]+):?[\s]+/gm
const match = [...content.matchAll(exportRegExp)]
const findings = match.reduce((acc, match) => {
const newFinding = {
model: match[1],
component: match[2],
}
acc.push(newFinding)
return acc
}, [])
exports.push(generateExport(file, findings))
})
const formatedContent = format(exports.join('\n'))
fs.writeFileSync(outputFile, formatedContent)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment