Last active
July 18, 2023 15:37
-
-
Save wlkns/75723a5ac81afac9127a4634912849ef to your computer and use it in GitHub Desktop.
Package up Vue components & exports into index.js (no deps, tested Node 18 LTS)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { readdir, readFile, writeFile } from 'node:fs/promises'; | |
const parseDir = async (path, directoriesOnly) => { | |
return (await readdir(path, {withFileTypes: true})) | |
.filter(file => file.isDirectory() == directoriesOnly) | |
.map(file => file.name); | |
} | |
const determineImportExports = async ({dir, file}) => { | |
if ( file.endsWith('.vue') ) | |
{ | |
const componentName = file.substring(0, file.lastIndexOf('.')) | |
return {file, components: [componentName]}; | |
} | |
const contents = await readFile(`./${dir}/${file}`, {encoding: 'utf-8'}); | |
const m = new RegExp("export {([^}]+)}").exec(contents); | |
if ( ! m ) { | |
return false; | |
} | |
return {file, components: m[1].split(',').map(s => s.trim())} | |
}; | |
const generateImports = ({file, components}) => { | |
if (!components?.length) { | |
return ''; | |
} | |
if ( file.endsWith('.vue') ) { | |
return `import ${components[0]} from './${file}'` | |
} | |
return `import { ${components.join(', ')} } from './${file}'` | |
}; | |
const generateExports = ({components}) => { | |
return components.map(c => ` ${c}`).join(",\n") | |
}; | |
const dirs = await parseDir('./', true); | |
const fileTypes = ['.vue', '.ts', '.js']; | |
const ignoredFiles = ['index.ts', 'index.js']; | |
dirs.forEach(async dir => { | |
let files = (await parseDir(`./${dir}`, false)) | |
.filter(file => !ignoredFiles.some(ignored => file === ignored)) | |
.filter(file => fileTypes.some(type => file.endsWith(type))) | |
.map(file => ({dir, file})); | |
if ( files.length === 0 ) { | |
return; | |
} | |
let importExports = (await Promise.all(files.map(determineImportExports))).filter(({components}) => components?.length) | |
if ( importExports.length === 0 ) { | |
return; | |
} | |
const count = importExports.reduce((p, {components}) => p + components.length, 0) | |
const header = `// build-index of ./${dir} (${count})` | |
const imports = importExports.map(generateImports).join("\n"); | |
const exports = importExports.map(generateExports).join(",\n"); | |
const output = [header, imports, '', 'export {', exports, '}', ''].join("\n"); | |
await writeFile(`./${dir}/index.js`, output); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment