需求: 公司里前端初始项目有多个比如: 管理系统、electron、h5… 每次新项目都需要去找仓库里对应的基建代码?于是准备自搭一个脚手架,实现新项目时直接使用脚手架创建对应项目的模板。

采用monorepo的模式来管理脚手架、在这里只提供核心代码实现,废话不多说开干!开干!

1、初始化项目

 1mkdir test_cli
 2pnpm iniit
 3touch index.js

2、修改package内容

 1{
 2  "name": "create-test_cli", 
 3  "version": "1.0.0",
 4  "description": "",
 5  "bin": "index.js", 
 6  "scripts": {
 7    "test": "echo \"Error: no test specified\" && exit 1"
 8  },
 9  "keywords": [],
10  "type": "module", 
11  "author": "",
12  "license": "ISC"
13}

3、使用第三方包解析交互命令

使用prompts来解析命令,实现目标如通过vite创建项目,如图:

 1pnpm add prompts

index.js文件中

 1
 2const promptsOptions = [
 3  {
 4    type: "text", 
 5    name: "name",
 6    message: "project-name",
 7    validate(val) {
 8      if (!val) return "模板名称不能为空!";
 9      if (fs.existsSync(val)) return "项目名已存在";
10      return true;
11    },
12  },
13  {
14    type: "select", 
15    name: "template",
16    message: "select a framework",
17    choices: [
18      { title: "vue3-tdesign-white(纯净版管理系统)", value: "vue3tdWhite" },
19    ],
20  },
21];

使用prompts(promptsOptions)会返回一个promise<{name, template}> ,对象中name、templatepromptsOptions决定。

现在有拿到用户输入的所有指令值,就可以进行对应的逻辑操作

拉取代码

拿到指令值后,对应去拉取仓库代码

 1const gitClone = (gitUrl, name, option) => {
 2  const downSpinner = ora("正在下载模板...").start();
 3  return new Promise((resolve, reject) => {
 4    download(gitUrl, name, option, (err) => {
 5      if (err) {
 6        downSpinner.fail();
 7        console.log("err", chalk.red(err));
 8        reject(err);
 9        return;
10      }
11      downSpinner.succeed(chalk.green("模板下载成功!"));
12      console.log(`Done. Now run:\r\n`);
13      console.log(chalk.green(`cd ${name}`));
14      console.log(chalk.blue("npm install"));
15      console.log("npm run dev\r\n");
16      resolve();
17    });
18  });
19};
20const res = await prompts(promptsOptions);
21const gitList = {
22  vue3tdWhite: "http://****.git", 
23};
24const branch = "master"
25gitClone(`direct:${gitList[res.template]}#${branch}`, res.name, {
26    clone: true,
27  });

需要用到的依赖包安装 download-git-repo 是拉取代码的作用 ora 作为loading状态

 1pnpm add ora download-git-repo

发布包

将包发布到npm上后直接执行

 1npm create test_cli 
 2或者
 3npm init test_cli 

结束了!

个人笔记记录 2021 ~ 2025