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

1、项目背景

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

1.1 镜像仓库

npm (npmjs.com)vue

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

1.2 脚手架源码

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

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

1.3 框架模板源码

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

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

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

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

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

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

2、项目演示

2.1 全局安装

$ npm install ncun-cli -g 
复制代码

2.2 检测安装

$ ncun
复制代码

在这里插入图片描述

2.3 查看版本

$ ncun -v
复制代码

在这里插入图片描述

2.4 建立项目

$ ncun init
复制代码

在这里插入图片描述

2.5 打开项目

在这里插入图片描述

2.6 启动项目

在这里插入图片描述

2.7 访问项目

在这里插入图片描述

3、需求分析

​ 因为公司内部基本都有私服的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、开发实现

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!'))
});

复制代码

5、项目总结

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

相关文章
相关标签/搜索