上篇文章主要記錄了從 GitHub 上下載模板文件用狱,這次主要記錄用 Metalsmith 和 Handlebars 修改模板文件。
參考
模板文件
之前的模板文件是靜態(tài)的杯聚,下載下來后直接就使用了∽蛞洌現(xiàn)在我想根據(jù)用戶輸入惶洲,將 package.json 的 name 改了。很簡單裹粤,使用 handlebar 的語法终蒂,將package.json 的 name 改成如下:
……
"name": "{{projectName}}",
……
這樣子蜂林,Handlebars 在編譯時就會使用 metadata 里的 projectName 的值了。其他的一樣的道理拇泣,這里只以 name 為例噪叙。
Metalsmith 和 Handlebars
首先安裝:
npm install metalsmith handlebars
首先在 lib 下創(chuàng)建一個 generator.js 文件,在 go 函數(shù)中調(diào)用即可霉翔。修改模板的的功能在 generator.js 中實現(xiàn)睁蕾。修改模板分為以下幾步:
- 下載模板文件(已實現(xiàn))
- 將文件內(nèi)容提取出來,轉(zhuǎn)換為字符串
- 使用 handlebar 將模板內(nèi)容字符串替換成用戶輸入的值
- Metalsmith build 成最終文件
- 刪除下載下來的模板文件
//generator.js
const Metalsmith = require('metalsmith')
const Handlebars = require('handlebars')
const rm = require('rimraf').sync
const chalk = require('chalk')
const _ = require('lodash')
module.exports = function(metadata = {}, source, destination = '.') {
if (!source) {
return Promise.reject(new Error(`無效的source:${source}`))
}
return new Promise((resolve, reject) => {
Metalsmith(process.cwd())
.metadata(metadata) //metadata 為用戶輸入的內(nèi)容
.clean(false)
.source(source) //模板文件 path
.destination(destination) //最終編譯好的文件存放位置
.use((files, metalsmith, done) => {
Object.keys(files).forEach(fileName => { //遍歷替換模板
if (!_.startsWith(fileName, 'src/font')) { //判斷是否為字體文件债朵,字體文件不用替換
const fileContentsString = files[fileName].contents.toString() //Handlebar compile 前需要轉(zhuǎn)換為字符創(chuàng)
files[fileName].contents = new Buffer(Handlebars.compile(fileContentsString)(metalsmith.metadata()))
}
})
done()
}).build(err => { // build
rm('source') //刪除下載下來的模板文件子眶,‘source’是路徑
if (err) {
console.log(chalk.red(`Metalsmith build error: ${err}`))
return reject(err)
} else {
return resolve()
}
})
})
}
需要注意的是,字體文件序芦、圖片等不能用 handlebar 替換臭杰。需要判斷一下。
到這里谚中,模板文件應(yīng)該就替換成功了渴杆。