思路流程图
使用到的工具
开始搭建脚手架的主要思路和关键代码
根据用户的终端输入,拿到全局配置信息
program
.version(packageJson.version) // 传入版本信息, node index.js --version/-V
.usage(`${chalk.green('<project-name>')} [options]`)
.option('-t --template <template-name>', '请选择模板名称')
.option('-r --templateRepoUrl <template-repo-url>', '远程模板仓库的链接')
.description('来自woyao用脚搭建的脚手架')
.action(function (path, cmd) {
// 输出校验
})
.on('--help', function () {
howToUse('<project-name>')
})
.parse(process.argv)
const projectName = program.args[0]
const templateRepoUrl = program.templateRepoUrl
拷贝远程模板仓库
function gitCloneRepository(templateRepoUrl) {
return new Promise(function (resolve, reject) {
log(`${chalk.green('开始拉取模板仓库')}`)
const command = 'git'
const args = [
'clone',
templateRepoUrl || `https://gitee.com/chenwoyao/woyao_templates.git`,
path.join(cliRoot, 'temp')
]
const child = spawn(command, args, { stdio: 'inherit' })
child.on('close', (code) => {
if (code !== 0) {
reject(`确保你有该远程模板仓库的权限或者你的远程仓库地址是否有误`)
return
}
console.log(`${chalk.green('模板仓库拉取成功')}`)
resolve()
})
})
}
选择模板
function choiceTemplate(dirs) {
return inquirer.prompt([{
name: 'template',
message: '请选择你要使用的模板',
type: 'list',
choices: dirs,
}])
.then(answer => {
return answer
})
}
将模板嵌入待建项目中
function copyTemplate(templateName, appRoot) {
return new Promise((resolve, reject) => {
console.log(`\n${chalk.greenBright('拷贝模板...')}`)
const templatePath = path.join(
cliRoot,
'temp',
'templates',
templateName
)
if (fs.existsSync(templatePath)) {
fs.copySync(templatePath, appRoot)
util.createDirTree(appRoot, ['node_modules', '.vscode', '.git'])
console.log(`${chalk.greenBright('模板拷贝完成...')}\n`)
resolve()
} else {
reject(`未能找到模板: ${templateName}`)
return
}
})
}
发布npm包
-
创建一个npm账号(用户名,邮箱,密码)
-
初始化项目
mkdir <projectName> && cd <projectName>npm initnpm adduse
-
npm publish
注意事项:
在发布的时候确保自己的npm官方源: npm config set registry https:*//registry.npmjs.org
之后在切换到淘宝源: npm config set registry https:*//registry.npm.taobao.org 我这边即使切换成淘宝源安装node-sass和sass-loader这两个包的时候也很慢。所以我直接用yarn了。 用cnpm管理工具安装的时候总会有警告信息打印出来,所以索性不用了。
如果登录过期了或者想切换用户,输入npm login重新登录