超干,搭建前端脚手架

757 阅读2分钟

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

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

1、初始化项目

mkdir test_cli
pnpm iniit
touch index.js

2、修改package内容

{
  "name": "create-test_cli", // 加“create-”前缀
  "version": "1.0.0",
  "description": "",
  "bin": "index.js", // 去除main属性 添加bin:index.js
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "type": "module", // type设置为module
  "author": "",
  "license": "ISC"
}

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

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

image.png

pnpm add prompts

index.js文件中

// 交互命令配置 
const promptsOptions = [
  {
    type: "text", //单选
    name: "name",
    message: "project-name",
    validate(val) {
      if (!val) return "模板名称不能为空!";
      if (fs.existsSync(val)) return "项目名已存在";
      return true;
    },
  },
  {
    type: "select", //单选
    name: "template",
    message: "select a framework",
    choices: [
      { title: "vue3-tdesign-white(纯净版管理系统)", value: "vue3tdWhite" },
    ],
  },
];

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

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

拉取代码

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

const gitClone = (gitUrl, name, option) => {
  const downSpinner = ora("正在下载模板...").start();
  return new Promise((resolve, reject) => {
    download(gitUrl, name, option, (err) => {
      if (err) {
        downSpinner.fail();
        console.log("err", chalk.red(err));
        reject(err);
        return;
      }
      downSpinner.succeed(chalk.green("模板下载成功!"));
      console.log(`Done. Now run:\r\n`);
      console.log(chalk.green(`cd ${name}`));
      console.log(chalk.blue("npm install"));
      console.log("npm run dev\r\n");
      resolve();
    });
  });
};
const res = await prompts(promptsOptions);
const gitList = {
  vue3tdWhite: "http://****.git", // 公司仓库代码地址
};
const branch = "master"
gitClone(`direct:${gitList[res.template]}#${branch}`, res.name, {
    clone: true,
  });

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

pnpm add ora download-git-repo

发布包

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

npm create test_cli 
或者
npm init test_cli 

image.png

结束了!