sk2-gulp-pages
sk2-gulp-cli模板文件生成器
使用
-
yarn add sk2-gulp-pages -D
ornpm install sk2-gulp-pages -D
-
yarn sk2-gulp-pages
, 根据命令行输入相关配置项 - 等待文件生成即可,集成了sk2-gulp-cli
实现
step 1. 通过inquirer实现命令行交互,生成ejs模板备用数据
inquirer.prompt([{
type: 'input',
name: 'projectName',
message: 'Please input your project(folder) name:'
}, {
type: 'input',
name: 'description',
message: 'Please input your project description:'
}, {
type: 'input',
name: 'homepage',
message: 'Please input your project homepage:'
} ...省略
step 2. 使用fs模块复制template下的文件至目标目录
// answers为命令行交互的文件
answers.projectName = answers.projectName || 'gulp-pages';
const projectName = answers.projectName;
// 获取命令行下要写入的文件夹路径
const distPath = resolve(process.cwd(), projectName);
fs.access(distPath, constants.F_OK, (err => {
if (err) {
// 未找到文件夹,直接安装
install();
} else {
// 已有文件夹,询问是否继续
inquirer.prompt([{
message: `${projectName} folder already exists, do you want to remove it`,
name: 'isRemove',
type: 'confirm',
}]).then(({isRemove}) => {
if (isRemove) {
// 继续,删除已有文件夹并安装
fs.rmSync(distPath, {recursive: true, force: true});
console.log(`${projectName} existing folder removed`);
install();
} else {
throw new Error('init error:aborted');
}
})
}
}))
其中install方法如下
function install() {
console.log('installation started');
fs.mkdirSync(distPath);
// 递归拷贝文件与文件夹
copy(templatePath, distPath, answers);
console.log(`done, hope you enjoy!`);
}
copy方法将template文件夹的内容(模板文件)拷贝至目标目录(命令行执行目录+用户通过命令行输入的文件夹名称)
function copy(src, dist, templateData) {
fs.readdir(src, (err, paths) => {
if (err) {
console.log('readdir error', src);
return;
}
paths.forEach(path => {
//src子文件/文件夹路径
const srcPath = resolve(src, path);
//dist子文件/文件夹路径
const distPath = resolve(dist, path);
fs.stat(srcPath, (err, stats) => {
// 如果是文件夹
if (stats.isDirectory()) {
// 先同步创建dist子文件夹
fs.mkdirSync(distPath);
// 递归执行方法
copy(srcPath, distPath, templateData);
} else if (stats.isFile()) {
// 如果是文件
fs.readFile(srcPath, (err, data) => {
if (err) {
console.log('readFile error', srcPath);
return;
}
// 通过ejs编译
const template = ejs.compile(data.toString());
// 写入文件
fs.writeFile(distPath, template(templateData), 'utf-8', () => {
if (err) {
console.log('writeFile error', distPath);
}
})
})
}
})
})
})
}
具体请见bin\index.js