开发Node CLI构建微信小程序脚手架的示例

2020-06-17 08:02:04易采站长站整理
+ 根据环境(
yarn
/
npm
/
cnpm
)安装依赖,这个就很简单了


const { exec } = require("child_process");
const ora = require("ora");
const chalk = require("chalk");

// proPath 项目目录
process.chdir(proPath);

// git init
const gitInitSpinner = ora(
`cd ${chalk.cyan.bold(projectName)}, 执行 ${chalk.cyan.bold("git init")}`
).start();

const gitInit = exec("git init");
gitInit.on("close", code => {
if (code === 0) {
gitInitSpinner.color = "green";
gitInitSpinner.succeed(gitInit.stdout.read());
} else {
gitInitSpinner.color = "red";
gitInitSpinner.fail(gitInit.stderr.read());
}
});

// install
let command = "";
if (shouldUseYarn()) {
command = "yarn";
} else if (shouldUseCnpm()) {
command = "cnpm install";
} else {
command = "npm install";
}

log(" ".padEnd(2, "n"));
const installSpinner = ora(
`执行安装项目依赖 ${chalk.cyan.bold(command)}, 需要一会儿...`
).start();

exec(command, (error, stdout, stderr) => {
if (error) {
installSpinner.color = "red";
installSpinner.fail(chalk.red("安装项目依赖失败,请自行重新安装!"));
console.log(error);
} else {
installSpinner.color = "green";
installSpinner.succeed("安装成功");
log(`${stderr}${stdout}`);
}
});

主要的代码就是这些,其实只要知道思路,这些东西都很简单,虽然我写的有点 ️:chicken:,但是主要的逻辑还是能理清楚的一些的。更加详细的可以去:eyes:我发的源码,多谢指教。:pray::pray::pray:

开发脚手架

因为这是小程序的脚手架,它不像其他

web
框架一样需要很多
webpack
的配置,所以相对简单很多。

对于这个脚手架,相比于开发者工具创建的默认项目,我弥补了它的一些问题

默认项目太过简单,只适合自己折腾,对于团队或者企业,缺乏相应的代码约定/规范,没有强制的约定会导致团队协作间的困难,提升code review的难度,所以我在原来的基础上加入了eslint,stylelint,prettier,commitlint等配置,以及git hook 在 pre-commit 时,执行校验,确保提交的代码尽量规范
由于对 css 预处理的钟爱,另外加入了对 less 的支持,并且解决小程序背景图不支持本地图片的问题
由于以上基本都是文件处理,所以选择 gulp 作为构建工具,这里是 v4, 与v3 写法上有一定的区别,不过关系不大

在根目录下创建

gulpfile.js