背景
平时在项目开发中,大多数人是没有习惯写注释或者在写组件时的组件解释的。这导致工作交接或者组件推广时不能友好的使用。
痛点
想到这里,基于项目开发迭代的越来越快,项目越来越大的情况下,写好一份完整的代码注解显得尤为重要。
所以我选择使用md文件的形式进行记录,但是由于项目目录较多,我需要一个文件夹一个文件夹的点开,然后再一个一个的创建,最后在找到相应文件目录下的某个md文件进行撰写md文件..... 一整套操作下来,好家伙!光创建文件夹到开始写就用了10分钟,这让准备写项目注解的程序员渐渐合上了电脑~ 还写个der啊!,所以这就导致了巨(屎)石(山)项目给后面负责交接的同学头昏脑胀。
如何解决
优秀的程序员总是喜欢偷懒的,当然这里的偷懒是偷懒但又不完全偷懒。利用好脚本,我们能够节省很多做无用功的时间来搬更多的砖。=,=@!
正文
废话不多说,直接上才艺!(EGM,~
const fs = require('fs');
/**
* 配置文件
*/
const configs = {
auto: false,
fileContent: `
## 这里是标题
`, // 当auto为true时,自动填充该字段内容
template: [
{
path: '/pscWorld',
fileContent: `
## 这里是标题
`,
},
{
path: '/template',
fileContent: `
## 这里是标题
`,
},
],
};
const fileName = 'index.md';
function isDir(file) {
return `${process.cwd()}/${file}`.split('.').length !== 2 && !(/./.test(`${process.cwd()}/${file}`));
}
/**
* 写函数
*/
function writeFile(path, content) {
fs.writeFile(`${path}/${fileName}`, content, (err) => {
if (err) {
console.log('创建失败');
} else {
console.log('创建成功');
}
});
}
/**
* 读取目录函数
*/
function readDir() {
const dir = [];
const files = fs.readdirSync(process.cwd());
files.forEach((file) => {
if (isDir(file)) {
dir.push(file);
}
});
return dir;
}
/**
* 主要函数
*/
function run() {
if (configs.auto) {
const dirs = readDir();
for (let i = 0; i < dirs.length; i++) {
if (dirs.length === configs.template) {
const { fileContent } = configs.template[i];
writeFile(`${process.cwd()}/${dirs[i]}`, fileContent);
} else {
writeFile(`${process.cwd()}/${dirs[i]}`, configs.fileContent);
}
}
} else {
for (let i = 0; i < configs.template; i++) {
const { fileContent, path } = configs.template[i];
writeFile(`${process.cwd()}/${path}`, fileContent);
}
}
}
run();
解释一下
configs作用:当auto为true时,自动在脚本运行目录下的所有文件夹下创建md文件;反之,当为false时会读取template中的路径进行填充,fileContent为填充内容;
后记
本脚本还有优化以及拓展的空间,比如可不可以在指定的目录下自动创建具有模版的模版文件呢?(类似编辑器生成类型文件的形式)
又或者能不能一键添加组件或者页面到当前项目中呢?(添加router、page到相应的目录,类似vue-cli的功能)
想法多种多样,如何实现呢?基于本篇后续有机会将继续讨论如何从0到1实现一个Vue-cli~