如何搭建团队内部的脚手架

1,934 阅读3分钟

一、项目背景

​ 公司不同项目组,使用不同的技术框架(vue or react),即便是同一项目组不同开发人员由不同的开发习惯。最终会导致在项目结构混乱,给其他人员维护造成了一些不必须的维护成本。为此很多公司开始着手开发自己的脚手架用来初始化项目模板。(很多公司会放在自己的私服镜像上,这里演示的就给大家放到npm公共镜像上,供大家体验方便。)

1.1 镜像仓库

npm (npmjs.com)

浏览器打开,搜索 ncun-cli即可查看

1.2 脚手架源码

ncun-cli: 诺春博客主题开发脚手架 (gitee.com)

ncun-cli: 诺春博客主题开发脚手架 (github.com)

1.3 框架模板源码

ncun-cli-vue-demo: NCun主题模板(Vue) (gitee.com)

ncun-cli-vue-demo: NCun主题模板(Vue) (github.com)

ncun-cli-react-demo: NCun主题模板(React) (gitee.com)

ncun-cli-react-demo: NCun主题模板(React) (github.com)

ncun-cli-angular-demo : NCun主题模板(Angular)(gitee.com)

ncun-cli-angular-demo : NCun主题模板(Angular)(github.com)

二、项目演示

2.1 全局安装

$ npm install ncun-cli -g 

2.2 检测安装

$ ncun

在这里插入图片描述

2.3 查看版本

$ ncun -v

在这里插入图片描述

2.4 创建项目

$ ncun init

在这里插入图片描述

2.5 打开项目

在这里插入图片描述

2.6 启动项目

在这里插入图片描述

2.7 访问项目

在这里插入图片描述

三、需求分析

​ 由于公司内部基本都有私服的gitlab,故我们把每个技术框架的模板放到私服仓库上,每个前端开发人员需要初始化新的项目时,使用公司的脚手架,选择自己的技术框架,就能初始化一个通用的模板。(这里主要演示如何实现一个脚手架,如果你有总公司git的访问权限,其实你可以直下载模板使用即可,一般每个部门又有部门的私有仓库,仅供部门成员访问。)

3.1 commander

​ node.js的命令行解决方案,用于自定义命令(如:ncun -v

3.2 inquirer

​ 一个用户与命令行交互工具,用于自定义项目名(如:? Project name:

3.3 shelljs

​ 重新包装了child_process,调用系统命令更加简单(如:git clone ...

3.4 ora

​ 实现node.js 命令行环境的 loading效果, 和显示各种状态的图标

3.5 chalk

​ 终端字符串样式插件,可改变终端字符串的颜色(如:chalk.green('NCun init successfully. Now run:')

四、开发实现

4.1 创建脚手架仓库

​ 在github上创建ncun-cli仓库,在本地克隆下来。

$ git clone https://github.com/dianjiu/ncun-cli.git

4.2 初始化项目

​ 此时是一个空项目,我们进行一下初始化。

$ npm init -y

4.3 修改配置

​ 此时项目中会出一个package.json文件,这里我们进行简单修改。

{
  "name": "ncun-cli",
  "version": "21.06.09",
  "description": "Command line interface for Ncun",
  "main": "lib/ncun",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/dianjiu/ncun-cli"
  },
  "homepage": "https://ncun.fun/",
  "keywords": [
    "blog",
    "cms",
    "ncun",
    "cli"
  ],
  "author": {
    "name": "DianJiu",
    "email": "dianjiu@dianjiu.cc",
    "url": "https://dianjiu.co"
  },
  "bin": {
    "ncun": "bin/ncun"
  },
  "bugs": {
    "url": "https://github.com/dianjiu/ncun-cli/issues"
  },
  "license": "MIT",
  "dependencies": {
  }
}

4.4 添加依赖

​ 然后我们添加下项目的基础依赖

$ npm install commander inquirer shelljs ora chalk --save

4.5 优化目录

​ 在根目录创建bin,lib文件夹和README.mdtemplates.json文件,在bin目录下新建ncun.js文件,在lib文件夹下新建ncun.jscommands文件夹,在commands文件夹下新建init.js文件。目录结构如下:

在这里插入图片描述

4.6 实现命令提示

​ 利用commander插件实现命令提示及基础命令功能。(/bin/ncun.js)实现代码如下:

#!/usr/bin/env node

'use strict';

// const manager = require('../lib/');
// manager.versions();
// console.log(1)
const program = require("commander");
const version = require("../package.json").version;

program
  .version(version, "-v, --version","output the current version")
  // 重写覆盖默认的帮助标识和描述
  .helpOption('-h, --help', 'read more information');

program
  .usage('<command>');

program
  .command('init')
  .description("init a ncun blog theme template ")
  .alias('i')
  .action(() => {
    require('../lib/commands/init')
  });

program.parse(process.argv);

if(!program.args.length){
    program.help()
}

4.7 配置模板仓库

​ 在templates.json中配置不同框架的模板仓库地址及代码分支。

{
	"tpl": {
		"vue": {
			"url": "https://github.com/dianjiu/ncun-cli-vue-demo.git",
			"branch": "master"
		},
		"react": {
			"url": "https://github.com/dianjiu/ncun-cli-react-demo.git",
			"branch": "master"
		},
		"angular": {
			"url": "https://github.com/dianjiu/ncun-cli-angular-demo.git",
			"branch": "master"
		}
	}
}

4.7 实现初始化功能

​ 在(/lib/commands/init.js)中实现功能,代码如下:

const { prompt } = require('inquirer');
const program = require('commander');
const shell = require('shelljs');
const ora = require('ora');
const fs = require('fs');
const config = require('../../templates.json')
const chalk = require('chalk')

const option =  program.parse(process.argv).args[0];
const question = [
  {
    type: 'input',
    name: 'template',
    message: 'Template name (you can input one like react, vue, angular):',
    default: typeof option === 'string' ? option : 'ncun-blog-template',
    filter (val) {
      return val.trim()
    },
    validate (val) {
      //检验模板中是否存在
      const validate = config.tpl[val];
      if(validate){
        return true
      }
      return chalk.red('Template does not support!');
    },
    transformer (val) {
      return val;
    }
  },
  {
    type: 'input',
    name: 'name',
    message: 'Project name',
    default: typeof option === 'string' ? option : 'ncun-blog-template',
    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;
    }
  },
  {
    type: 'input',
    name: 'description',
    message: 'Project description',
    default: 'Vue project',
    validate () {
      return true;
    },
    transformer(val) {
      return val;
    }
  },
  {
    type: 'input',
    name: 'author',
    message: 'Author',
    default: '',
    validate () {
      return true;
    },
    transformer(val) {
      return val;
    }
  }
];

module.exports = prompt(question).then(({template, name, description, author}) => {
  gitUrl = config.tpl[template].url
  branch = config.tpl[template].branch
  const projectName = name;
  const spinner = ora('Downloading please wait... \n');

  spinner.start();
  //克隆模板
  let cmdStr = `git clone -b ${branch} ${gitUrl} ${projectName} `
  // childProcess.exec(cmdStr, function(error, stdout, stderr){
  if(shell.exec(cmdStr).code !== 0){
    shell.echo('Error: Git clone failed');
    shell.exit(1);
  }
  
  
  //读取package.json
  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;
    
    //修改package.json
    fs.writeFile(`./${projectName}/package.json`, JSON.stringify(packageJson, null, 2), 'utf8', function (err) {
      if(err) {
        spinner.stop();
        console.error(err);
      } else {
        spinner.stop();
        console.log(chalk.green('NCun init successfully. Now run:'))
        console.log(`
          ${chalk.yellow(`cd ${projectName}`)}
          ${chalk.yellow('npm install (or `yarn`)')}
          ${chalk.yellow('npm run dev (or `yarn dev`)')}
        `);
      }
    });
  });

  console.log(chalk.green('\n √ Generation completed!'))
});

五、项目总结

​ 目前项目仅做了简单的实现,且仅支持了vue模板,后续会持续更新优化。具体大家可根据自己的开发习惯进行定制自己的项目模板。本地下载脚手架源码后,替换模板仓库地址为你自己的,使用npm link进行本地模拟调试。