Skip to content

Instantly share code, notes, and snippets.

@wangpin34
Created May 12, 2022 02:52
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 wangpin34/0e49694ecd63f0d17683cb98774e290d to your computer and use it in GitHub Desktop.
Save wangpin34/0e49694ecd63f0d17683cb98774e290d to your computer and use it in GitHub Desktop.
yargs sample to create command like `npm create-react-app appName
#!/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