UNPKG

unbundle

Version:

import/export & node_modules in the browser, without the bundling

90 lines (85 loc) 2.62 kB
#!/usr/bin/env node const unbundle = require('./unbundle') const yargs = require('yargs') const chalk = require('chalk') const { constants: { COPYFILE_EXCL }, promises: { writeFile, mkdir, copyFile } } = require('fs') const { resolve, dirname, relative, join } = require('path') async function main () { const { argv } = yargs .option('entry', { type: 'string', alias: 'i', demandOption: true, describe: 'File path of source code entry point' }) .option('destination', { type: 'string', alias: 'o', demandOption: true, describe: 'Directory path to write output' }) .option('root', { type: 'string', describe: 'Prefix path for `node_modules`', default: '/' }) .option('force', { type: 'boolean', alias: 'f', describe: 'Overwrite existing files', default: false }) .option('recurse', { type: 'boolean', alias: 'r', describe: 'Recursively trace all files', default: true }) .option('verbose', { type: 'boolean', describe: 'Show more information during file processing', default: false }) .example('--entry ./src/app.js --destination ./dist') .example('Trace all dependencies of app.js and output to dist directory.') .example('') .example('--entry index.js --destination public/assets/scripts --root /assets/scripts/') .example('Prefix imports of NPM packages with: /assets/scripts/node_modules/') .version() .help() const destination = resolve(argv.destination) const files = unbundle(argv.entry, argv) await mkdir(destination, { recursive: true }) for (const file of files.values()) { console.log(file.to) const to = join(destination, file.to) await mkdir(dirname(to), { recursive: true }) try { await writeFile(to, file.code, { flag: argv.force ? 'w' : 'wx' }) if (argv.verbose) console.log(`File: ${file.to}`) if (file.map) { const fromMap = resolve(dirname(file.from), file.map) const toMap = resolve(dirname(to), file.map) await mkdir(dirname(toMap), { recursive: true }) await copyFile(fromMap, toMap, argv.force ? 0 : COPYFILE_EXCL) if (argv.verbose) console.log(`Map: ${relative(destination, toMap)}`) } } catch (error) { if (error.code === 'EEXIST') { throw new Error( `File exists at '${file.to}'. Use --force to overwrite.` ) } else { throw error } } } } main() .catch((error) => { console.trace(chalk.red(error)) process.exit(1) })