基于nodejs的脚手架工具开发经历
公司需要搭建一个cli工具,公司内部使用,查看了很多文档资料,找到了一篇讲的很好。大佬文章地址:
我在使用的时候遇到一个问题:在图片转换拷贝到目录的时候会出错。
// touch ./lib/generator.js
// npm i handlebars metalsmith -D
const Metalsmith = require('metalsmith')
const Handlebars = require('handlebars')
const rm = require('rimraf').sync
module.exports = function (metadata = {}, src, dest = '.') {
if (!src) {
return Promise.reject(new Error(`无效的source:${src}`))
}
return new Promise((resolve, reject) => {
Metalsmith(process.cwd())
.metadata(metadata)
.clean(false)
.source(src)
.destination(dest)
.use((files, metalsmith, done) => {
const meta = metalsmith.metadata()
Object.keys(files).forEach(fileName => {
const t = files[fileName].contents.toString()
files[fileName].contents = new Buffer(Handlebars.compile(t)(meta))
})
done()
}).build(err => {
rm(src)
err ? reject(err) : resolve()
})
})
}
在上面代码这一步中,在把临时文件拷入项目中。
const meta = metalsmith.metadata()
Object.keys(files).forEach(fileName => {
const t = files[fileName].contents.toString()
files[fileName].contents = new Buffer(Handlebars.compile(t)(meta))
})
这一步是把用户交互录入的变量(name,version,description等),给置换到我们的项目中。因为图片转toString()问题,导致老是出错。后来想想图片没什么好置换的,加了trycatch把他解决了。
const meta = metalsmith.metadata()
Object.keys(files).forEach(fileName => {
try {
const t = files[fileName].contents.toString()
files[fileName].contents = new Buffer.from(Handlebars.compile(t)(meta))
} catch (error) {
return;
}
})
接着就是要把项目发布到npm上,网上都可以搜到。这边就随便贴一个:
自己写了一个demo在码云上: