在工做中咱们会用到不少便捷的脚手架工具,好比Vue的vue-cli,React的create-react-app等。极大的提升了咱们的工做效率,那么今天咱们就来学学怎么制做一款自用的前端脚手架。前端
在根目录下新建
bin/luchx.js
文件,并添加如下代码vue
#!/usr/bin/env node
// Check node version before requiring/doing anything else
// The user may be on a very old node version
const chalk = require('chalk')
const program = require('commander')
program
.version(require('../package').version)
.usage('<command> [options]')
program.parse(process.argv)
if (!process.argv.slice(2).length) {
program.outputHelp()
}
复制代码
首先文件第一行表示该文件运行于node环境,接着引入commander。最后的program.parse方法用于解析命令行中传入的参数。node
command命令有两种用法,官方示例以下:react
// Command implemented using action handler (description is supplied separately to `.command`)
// Returns new command for configuring.
program
.command('clone <source> [destination]')
.description('clone a repository into a newly created directory')
.action((source, destination) => {
console.log('clone command called');
});
// Command implemented using separate executable file (description is second parameter to `.command`)
// Returns top-level command for adding more commands.
program
.command('start <service>', 'start named service')
.command('stop [service]', 'stop named service, or all if no name supplied');
复制代码
其中参数对应的<>, [ ]分别表明必填和选填。这里咱们使用第一种,添加以下代码:git
program
.command('create <app-name>')
.description(' Create a project with template already created.')
.action((name, cmd) => {
require('../lib/create')(name)
})
复制代码
// add some useful info on help
program.on('--help', () => {
console.log()
console.log(` Run ${chalk.cyan('luchx <command> --help')} for detailed usage of given command.`)
console.log()
})
复制代码
执行结果github
module.exports = async function create (projectName) { }
复制代码
const path = require('path')
const fs = require('fs-extra')
const inquirer = require('inquirer')
const chalk = require('chalk')
const validateProjectName = require('validate-npm-package-name')
module.exports = async function create (projectName) {
const cwd = process.cwd()
const targetDir = path.resolve(cwd, projectName)
const name = path.relative(cwd, projectName)
const result = validateProjectName(name)
if (!result.validForNewPackages) {
console.error(chalk.red(`Invalid project name: "${name}"`))
result.errors && result.errors.forEach(err => {
console.error(chalk.red.dim('Error: ' + err))
})
result.warnings && result.warnings.forEach(warn => {
console.error(chalk.red.dim('Warning: ' + warn))
})
process.exit(1)
}
if (fs.existsSync(targetDir)) {
const { action } = await inquirer.prompt([
{
name: 'action',
type: 'list',
message: `Target directory ${chalk.cyan(targetDir)} already exists. Pick an action:`,
choices: [
{ name: 'Overwrite', value: 'overwrite' },
{ name: 'Cancel', value: false }
]
}
])
if (!action) {
return
} else if (action === 'overwrite') {
console.log(`\nRemoving ${chalk.cyan(targetDir)}...`)
await fs.remove(targetDir)
}
}
// ...
}
复制代码
const inquirer = require('inquirer')
module.exports = async function create (projectName) {
// ...
const { bolierplateType, author, description, version } = await inquirer.prompt([
{
name: 'bolierplateType',
type: 'list',
default: 'vue',
choices: [
{
name: 'Vue',
value: 'vue'
},
{
name: 'React',
value: 'react'
}
],
message: 'Select the boilerplate type.'
}, {
type: 'input',
name: 'description',
message: 'Please input your project description.',
default: 'description',
validate (val) {
return true
},
transformer (val) {
return val
}
}, {
type: 'input',
name: 'author',
message: 'Please input your author name.',
default: 'author',
validate (val) {
return true
},
transformer (val) {
return val
}
}, {
type: 'input',
name: 'version',
message: 'Please input your version.',
default: '0.0.1',
validate (val) {
return true
},
transformer (val) {
return val
}
}
])
// ...
}
复制代码
const download = require('download-git-repo')
module.exports = function downloadFromRemote (url, name) {
return new Promise((resolve, reject) => {
download(`direct:${url}`, name, { clone: true }, function (err) {
if (err) {
reject(err)
return
}
resolve()
})
})
}
复制代码
const fs = require('fs-extra')
const chalk = require('chalk')
const logSymbols = require('log-symbols')
const downloadFromRemote = require('../lib/downloadFromRemote')
module.exports = async function create (projectName) {
// ...
downloadFromRemote(remoteUrl, projectName).then(res => {
fs.readFile(`./${projectName}/package.json`, 'utf8', function (err, data) {
if (err) {
spinner.stop()
console.error(err)
return
}
const packageJson = JSON.parse(data)
packageJson.name = projectName
packageJson.description = description
packageJson.author = author
packageJson.version = version
var updatePackageJson = JSON.stringify(packageJson, null, 2)
fs.writeFile(`./${projectName}/package.json`, updatePackageJson, 'utf8', function (err) {
spinner.stop()
if (err) {
console.error(err)
} else {
console.log(logSymbols.success, chalk.green(`Successfully created project template of ${bolierplateType}\n`))
console.log(`${chalk.grey(`cd ${projectName}`)}\n${chalk.grey('yarn install')}\n${chalk.grey('yarn serve')}\n`)
}
process.exit()
})
})
}).catch((err) => {
console.log(logSymbols.error, err)
spinner.fail(chalk.red('Sorry, it must be something error,please check it out. \n'))
process.exit(-1)
})
}
复制代码
本项目没有发布到npm上,仅做学习研究之用,能够本身拉取项目而后执行npm link,在本地体验。为了能够全局使用,咱们须要在package.json里面设置一下,这样就能够执行luchx命令开头的指令了。vue-cli
"bin": {
"luchx": "bin/luchx.js"
},
复制代码
以上完整的代码能够访问github查看获取npm