UNPKG

mytool-xjp

Version:

前端脚手架工具

38 lines (34 loc) 1.35 kB
// 把模板中的变量替换为用户输入的变量,输出模板到制定文件夹 const Metalsmith = require('metalsmith'); const Handlebars = require('handlebars'); const path = require('path'); const fs = require('fs'); const { askQuestion } = require('./askQuestion'); const loadTemplate = async () => { // 从toolrc.json文件读取配置 const dirPath = process.cwd(); if (!fs.existsSync('toolrc.json')) { throw new Error('toolrc.json配置文件不存在'); } const configJson = path.join(dirPath, 'toolrc.json'); const config = fs.readFileSync(configJson); const { source, dist, questionConfig } = JSON.parse(config); const answer = await askQuestion(questionConfig); const metalsmith = Metalsmith(__dirname); metalsmith .metadata(answer) .source(path.join(dirPath, source)) .destination(path.join(dirPath, dist)) .use(function (files, metalsmith, done) { //遍历替换模板 Object.keys(files).forEach(fileName => { const fileContentsString = files[fileName].contents.toString(); //Handlebar compile 前需要转换为字符串 files[fileName].contents = new Buffer(Handlebars.compile(fileContentsString)(metalsmith.metadata())); }); done(); }).build(function (err) { if (err) throw err; }); }; module.exports.loadTemplate = loadTemplate;