npm 搭建 自定义脚手架

244 阅读2分钟

自定义脚手架:react-young5-cli 的搭建

目标

react-young5-cli 是一个创建系统模板的 脚手架工具,可以通过npm可以直接安装,再通过脚手架可以直接创建并拉取自己编写的项目模板代码。

github 完整源码地址github.com/yangw5/reac… 🔥🔥🔥

注:npm 上的代码版本与 github 上保持一致。

下载克隆项目

git clone https://github.com/yangw5/react-young5-cli.git

项目依赖

  • chalk:提供命令颜色控制 👍
  • commander:提供了用户命令行输入和参数解析 👍
  • download-git-repo:下载并提取 git 仓库,用于下载项目模板 👍
  • inquirer:通用的命令行用户界面集合,用于和用户进行交互 👍
  • ora:微调节器:图标等的自定义 👍
  • 等等

相关依赖用法github.com/yangw5/docu…

代码目录

    + --bin/                            ---命令提示配置文件
    |    --- react-cli.js
    + --commands/                       --- 命令定义文件
    |    --- init.js
    + .gitignore                        ---git提交忽略文件
    + .npmignore                        ---npm提交忽略文件
    + .package.json                     ---项目信息及相关依赖文件
    + .templates.json                   ---git 模板配置
    + .README.md                        ---项目说明文件

核心代码

packjson.json

  1. 创建项目

     node init
    
  2. 安装相关依赖

     npm install xxx
    
  3. 配置启动

      "bin": {
         "react-young5-cli": "bin/react-cli"
       },
    

react-cli

#!/usr/bin/env node
const { resolve } = require("path");
const program = require("commander");
process.env.NODE_PATH = __dirname + "/../node_modules/";
const res = command => resolve(__dirname, "../commands/", command);

program.version(require("../package").version);

program.usage("<command>");

program // node命令配置
  .command("init")
  .option("-f, --foo", "enable some foo")
  .description("Generate a new project")
  .alias("i")
  .action(() => {
    require(res("init"));
  });

program.parse(process.argv);

/**
 * program.argv:node文件地址 项目地址 参数
 * program.args:未定义参数
 */

if (!process.argv[2] || (process.argv[2] && program.args.length)) {
  program.help();
}

init.js

const { prompt } = require("inquirer");
const program = require("commander");
const chalk = require("chalk");
const download = require("download-git-repo");
const ora = require("ora");
const fs = require("fs");
const path = require("path");

const option = program.parse(process.argv).args[0];
const defaultName = typeof option === "string" ? option : "react-project";
const tplList = require(`${__dirname}/../templates`);
const tplLists = Object.keys(tplList) || [];
const question = [//用户交互配置
  {
    type: "input",
    name: "name",
    message: " your Project name",
    default: defaultName,
    filter(val) {
      return val.trim();
    },
    validate(val) {
      const validate = val.trim().split(" ").length === 1;
      return validate || "Project name is not allowed to have spaces ";
    },
    transformer(val) {
      return val;
    }
  },
...
];
module.exports = prompt(question).then(
  ({ name, template, description, author }) => {
    const projectName = name;
    const templateName = template;
    const gitPlace = tplList[templateName]["place"];
    const gitBranch = tplList[templateName]["branch"];
    const spinner = ora("Downloading please wait...");
    spinner.start();
    //let cmdStr = `git clone ${gitUrl} ${projectName} && cd ${projectName} && git checkout ${branch}`
    //模板下载
    download(`${gitPlace}#${gitBranch}`, `./${projectName}`, err => {
      if (err) {
        console.log(chalk.red(err));
        process.exit();
      }
      fs.readFile(`./${projectName}/package.json`, "utf8", function(err, data) {
        if (err) {
          spinner.stop();
          console.error(err);
          return;
        }
        const packageJson = JSON.parse(data);
        packageJson.name = name;
        packageJson.description = description;
        packageJson.author = author;
        var updatePackageJson = JSON.stringify(packageJson, null, 2);
        fs.writeFile(   //package配置
          `./${projectName}/package.json`,
          updatePackageJson,
          "utf8",
          function(err) {
            if (err) {
              spinner.stop();
              console.error(err);
              return;
            } else {
              spinner.stop();
              console.log(chalk.green("project init successfully!"));
              console.log(`
            ${chalk.bgWhite.black("   Run Application  ")}
            ${chalk.yellow(`cd ${name}`)}
            ${chalk.yellow("npm install")}
            ${chalk.yellow("npm start")}
          `);
            }
          }
        );
      });
    });
  }
);

templates.json

{
  "react-web": {
    "place": "yangw5/react-web", //github上项目名称
    "branch": "master" //分支
  },
  ...
}

坑点

  1. 需要 npm 账号,推荐去官网进行注册
  2. npm 名要唯一

react-youngw-cli 的安装使用

  • npm 全局安装 react-youngw-cli

      npm i react-young-cli -g
    
  • 创建项目

      react-young5-cli i
    
  • 初始化并运行项目

      yarn
    
      yarn start
    

结尾

作者:young5

邮箱:yangw5@163.com

项目中存在的问题和有优化的地方,希望大家多多的指出。 如果有相关的疑惑,可以加入 QQ 群与我联系:

  • 254486893

赠人玫瑰,手有余香,希望对大家有所帮助,同时你觉得有所获得的话,那就戳一个 star 吧~~❤️❤️❤️❤️❤️,感谢!