Created
May 12, 2022 02:52
-
-
Save wangpin34/0e49694ecd63f0d17683cb98774e290d to your computer and use it in GitHub Desktop.
yargs sample to create command like `npm create-react-app appName
This file contains 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
#!/usr/bin/env node | |
import path from 'path' | |
import yargs from 'yargs/yargs' | |
import fs from 'fs/promises' | |
import figlet from 'figlet' | |
import chalk from 'chalk' | |
import init from './command-init' | |
import packageJSON from '../package.json' | |
import { setLevel, Level } from 'utils/logger' | |
import { GlobalOptions } from 'command-init/types' | |
async function generateBrand() { | |
return new Promise((resolve, reject) => { | |
figlet(packageJSON.displayName || packageJSON.name, (err, data) => { | |
if (err) { | |
reject(err) | |
} | |
resolve(data) | |
}) | |
}) | |
} | |
const bin = 'create-horizon-app' | |
yargs(process.argv.slice(2)) | |
.command('$0', '<project-directory> [options]', {}, async (argv) => { | |
const projectDir = process.argv[2] | |
if (!projectDir) { | |
console.log( | |
`Please specify the project directory:\n`, | |
` ${chalk.hex('#229bff').bold(bin)} ${chalk.green( | |
'<project-directory>' | |
)}\n\n`, | |
`For example:\n`, | |
` ${chalk.hex('#229bff').bold(bin)} ${chalk.green( | |
'my-horizon-app' | |
)}\n`, | |
`Run ${chalk.hex('#229bff').bold(bin + ' --help')} to see all options.` | |
) | |
return | |
} | |
if (argv.verbose) { | |
setLevel(Level.verbose) | |
} | |
const brand = await generateBrand() | |
console.log(brand) | |
const head = await fs.readFile( | |
path.join(__dirname, '../head-of-init'), | |
'utf-8' | |
) | |
console.log(chalk.blue(head)) | |
await fs.mkdir(projectDir) | |
process.chdir(projectDir) | |
init({ verbose: argv.verbose, beta: argv.beta } as GlobalOptions) | |
}) | |
.option('verbose', { | |
type: 'boolean', | |
description: 'Run with verbose logging', | |
}) | |
.option('beta', { | |
type: 'boolean', | |
description: `Try new features, including realtime create-react-app`, | |
}) | |
.demandCommand() | |
.help().argv |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment