前端脚手架,自动创建远程仓库并推送

2024-09-04 04:04

本文主要是介绍前端脚手架,自动创建远程仓库并推送,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

包含命令行选择和输入配置,远程仓库拉取模板,根据配置将代码注入模板框架的代码中,自动创建远程仓库,初始化git并提交至远程仓库,方便项目开发,简化流程。

目录结构

b29f2b9701c546a9b69285873f24d60e.png

创建一个bin文件夹,添加index.js文件,在这个文件中写下#! /usr/bin/env node

在package.json文件夹下

8172e131316244b0a33e2513d977e14e.png

执行 npm link 命令,链接到本地环境中 npm link (只有本地开发需要执行这一步,正常脚手架全局安装无需执行此步骤)Link 相当于将当前本地模块链接到npm目录下,这个目录可以直接访问,所以当前包就能直接访问了。默认package.json的name为基准,也可以通过bin配置别名。link完后,npm会自动帮忙生成命令,之后可以直接执行cli xxx。

直接上代码bin/index.js

#!/usr/bin/env nodeimport { Command } from 'commander';
import chalk from 'chalk';
import figlet from 'figlet';
import { promises as fs } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import Creater from '../lib/create.js';
import { getProjectName } from '../utils/index.js';  // 引入封装好的模块
import '../utils/utils.js'
// 解析 __dirname 和 __filename
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);// 异步读取 JSON 文件并解析
const packageJsonPath = path.resolve(__dirname, '../package.json');
const config = JSON.parse(await fs.readFile(packageJsonPath, 'utf-8'));const program = new Command();// 欢迎信息
console.log(chalk.green(figlet.textSync('Ti CLI', {horizontalLayout: 'full'
})));program.command('create').description('create a new project').option('-f, --force', 'overwrite target directory if it exists').action(async (options) => {// 获取工作目录const cwd = process.cwd();// 提示用户输入项目名称const projectName = await getProjectName(cwd);// 目标目录也就是要创建的目录const targetDir = path.join(cwd, projectName);const creater = new Creater(projectName, targetDir,'git密令');try {await creater.create();} catch (error) {console.error(chalk.red(`创建项目失败: ${error.message}`));}});program.command('build').description('build the project').action(() => {console.log('执行 build 命令');// 在这里实现 build 命令的具体逻辑});program.command('serve').description('serve the project').option('-p, --port <port>', 'specify port to use', '3000').action((options) => {console.log(`Serving on port ${options.port}`);// 在这里实现 serve 命令的具体逻辑});program.on('--help', () => {console.log();console.log(`Run ${chalk.cyan('thingjs-ti <command> --help')} to show detail of this command`);console.log();
});program.version(`thingjs-ti-cli@${config.version}`).usage('<command> [options]');program.parse(process.argv);

git密令那块儿填写自己的。

lib/create.js

import inquirer from 'inquirer';
import { exec } from 'child_process';
import { promisify } from 'util';
import { rm, cp } from 'fs/promises'; // 使用 fs/promises 模块
import { injectMainCode } from './injectCode.js';
import { fileURLToPath } from 'url'; // 引入 fileURLToPath
import axios from 'axios';
import path from 'path'; // 引入 path 模块const execPromise = promisify(exec);
// 使用 import.meta.url 获取当前模块的路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);class Creater {constructor(projectName, targetDir, gitlabToken) {this.name = projectName;this.dir = targetDir;this.gitlabToken = gitlabToken;this.parentGroupId = '你的群组id';this.subGroupId = null;this.options = null;this.isOnline = true;}async create() {try {this.isOnline = await this.chooseDownloadMode();const template = await this.chooseTemplate();if (template === '园区项目基础框架') {this.options = await this.chooseOptions();if (this.isOnline) {await this.downloadTemplate(template, this.options);} else {await this.copyTemplate(template, this.options);}console.log('项目创建完成');} else {if (this.isOnline) {await this.downloadTemplate(template);} else {await this.copyTemplate(template);}console.log('项目创建完成');}if (this.isOnline) {// 创建子群组await this.createSubGroup(this.options.projectFullName);// 在子群组中创建远程仓库await this.createRemoteRepository();}} catch (error) {console.error('创建项目失败:', error);}}async createSubGroup(subgroupName) {if (!this.gitlabToken) {throw new Error('GitLab Token 未设置,请确保已设置环境变量 GITLAB_TOKEN');}try {const response = await axios.post(`git地址`,{name: subgroupName,path: this.name,parent_id: this.parentGroupId,visibility: 'private' // 可以选择 'private' 或 'public'},{headers: {'Authorization': `Bearer ${this.gitlabToken}`,'Content-Type': 'application/json'}});this.subGroupId = response.data.id;console.log(`子群组创建成功: ${subgroupName}`);} catch (error) {console.error('创建子群组失败:', error);throw error;}}async createRemoteRepository() {if (!this.gitlabToken) {throw new Error('GitLab Token 未设置,请确保已设置环境变量 GITLAB_TOKEN');}if (!this.subGroupId) {throw new Error('子群组 ID 未设置,请确保子群组已创建');}try {const response = await axios.post('git地址',{name: `${this.name}-web`,namespace_id: this.subGroupId,visibility: 'private' // 可以选择 'private' 或 'public'},{headers: {'Authorization': `Bearer ${this.gitlabToken}`,'Content-Type': 'application/json'}});const repoUrl = response.data.ssh_url_to_repo;console.log(`远程仓库创建成功: ${repoUrl}`);// 初始化本地 Git 仓库并创建初始提交await execPromise(`cd ${this.dir} && git init`);await execPromise(`cd ${this.dir} && git add .`);await execPromise(`cd ${this.dir} && git commit -m "Initial commit"`);// 添加远程仓库并推送初始提交await execPromise(`cd ${this.dir} && git remote add origin ${repoUrl}`);await execPromise(`cd ${this.dir} && git push -u origin main`);} catch (error) {console.error('创建远程仓库失败:', error);throw error;}}async chooseOptions() {// 用户输入项目全称const { projectFullName } = await inquirer.prompt({type: 'input',name: 'projectFullName',message: '请输入项目全称(git群组名称):',validate: (input) => input ? true : '项目全称不能为空'});return {projectFullName };}async chooseTemplate() {const answers = await inquirer.prompt({type: 'list',name: 'template',message: '请选择项目模板:',choices: ['园区标准项目模板', '园区项目基础框架'],default: '园区项目基础框架'});return answers.template;}async chooseDownloadMode() {const answers = await inquirer.prompt({type: 'list',name: 'downloadMode',message: '请选择下载模式:',choices: ['在线', '离线'],default: '离线'});return answers.downloadMode === '在线';}async handleOptions(options) {await injectMainCode(this.dir, { needLogin: options.needLogin, width: options.width, height: options.height });}async downloadTemplate(template, options) {const repoUrls = {'园区标准项目模板': '模板git地址','园区项目基础框架': '模板git地址'};const repoUrl = repoUrls[template];if (!repoUrl) {throw new Error(`未知的模板: ${template}`);}try {console.log(`正在下载模板: ${repoUrl}`);await execPromise(`git clone ${repoUrl} ${this.dir}`);// 删除 .git 文件夹await rm(`${this.dir}/.git`, { recursive: true, force: true });if (template === '园区项目基础框架') {await this.handleOptions(options);}} catch (error) {console.error('模板下载失败:', error);throw error;}}async copyTemplate(template, options) {const templates = {'园区标准项目模板': path.resolve(__dirname, '../framework/ti-campus-template'),'园区项目基础框架': path.resolve(__dirname, '../framework/ti-project-template')};const templatePath = templates[template];if (!templatePath) {throw new Error(`未知的模板: ${template}`);}try {console.log(`正在复制模板: ${templatePath}`);await cp(templatePath, this.dir, { recursive: true });if (template === '园区项目基础框架') {await this.handleOptions(options);}} catch (error) {console.error('模板复制失败:', error);throw error;}}
}export default Creater;

注意替换git地址,请求的git接口可以自己看看gitlab文档,parentGroupId是指群组id,各个公司不一样的,可以根据自己的来。

lib/injectCode.js这个主要是向模板框架中注入配置项代码

import path from 'path';
import fs from 'fs/promises';
import prettier from 'prettier';async function injectMainCode(targetDir, options) {const mainTsPath = path.join(targetDir, 'src', 'main.ts');let loginCode ='';if(!options.needLogin){loginCode =‘你的代码’}else{loginCode = `你的代码`    }try {// 清空 main.ts 文件内容await fs.writeFile(mainTsPath, '', 'utf-8');// 读取 main.ts 文件let mainTsContent = await fs.readFile(mainTsPath, 'utf-8');if (!mainTsContent.includes('initLogin()')) {mainTsContent += loginCode;// 使用 Prettier 格式化代码const formattedContent = await prettier.format(mainTsContent, { parser: 'typescript' });await fs.writeFile(mainTsPath, formattedContent, 'utf-8');console.log('已向 main.ts 中注入登录功能代码');}} catch (error) {console.error('更新 main.ts 失败:', error);throw error;}
}export { injectMainCode };

utils/utils.js这里封装了一个工具函数

// 自定义 findLastIndex 函数
if (!Array.prototype.findLastIndex) {Array.prototype.findLastIndex = function (predicate, thisArg) {for (let i = this.length - 1; i >= 0; i--) {if (predicate.call(thisArg, this[i], i, this)) {return i;}}return -1;};
}

好了这就结束了,这就是一个很基础很简单的脚手架,可能日常工作需要更复杂更全面的,可以继续在上面叠加,我相信你看完起码觉的这也没什么难的了。

 

这篇关于前端脚手架,自动创建远程仓库并推送的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1134940

相关文章

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本

HTML5 搜索框Search Box详解

《HTML5搜索框SearchBox详解》HTML5的搜索框是一个强大的工具,能够有效提升用户体验,通过结合自动补全功能和适当的样式,可以创建出既美观又实用的搜索界面,这篇文章给大家介绍HTML5... html5 搜索框(Search Box)详解搜索框是一个用于输入查询内容的控件,通常用于网站或应用程

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

CSS3中的字体及相关属性详解

《CSS3中的字体及相关属性详解》:本文主要介绍了CSS3中的字体及相关属性,详细内容请阅读本文,希望能对你有所帮助... 字体网页字体的三个来源:用户机器上安装的字体,放心使用。保存在第三方网站上的字体,例如Typekit和Google,可以link标签链接到你的页面上。保存在你自己Web服务器上的字

MyBatis Plus 中 update_time 字段自动填充失效的原因分析及解决方案(最新整理)

《MyBatisPlus中update_time字段自动填充失效的原因分析及解决方案(最新整理)》在使用MyBatisPlus时,通常我们会在数据库表中设置create_time和update... 目录前言一、问题现象二、原因分析三、总结:常见原因与解决方法对照表四、推荐写法前言在使用 MyBATis

Java中实现线程的创建和启动的方法

《Java中实现线程的创建和启动的方法》在Java中,实现线程的创建和启动是两个不同但紧密相关的概念,理解为什么要启动线程(调用start()方法)而非直接调用run()方法,是掌握多线程编程的关键,... 目录1. 线程的生命周期2. start() vs run() 的本质区别3. 为什么必须通过 st

Python使用smtplib库开发一个邮件自动发送工具

《Python使用smtplib库开发一个邮件自动发送工具》在现代软件开发中,自动化邮件发送是一个非常实用的功能,无论是系统通知、营销邮件、还是日常工作报告,Python的smtplib库都能帮助我们... 目录代码实现与知识点解析1. 导入必要的库2. 配置邮件服务器参数3. 创建邮件发送类4. 实现邮件

html 滚动条滚动过快会留下边框线的解决方案

《html滚动条滚动过快会留下边框线的解决方案》:本文主要介绍了html滚动条滚动过快会留下边框线的解决方案,解决方法很简单,详细内容请阅读本文,希望能对你有所帮助... 滚动条滚动过快时,会留下边框线但其实大部分时候是这样的,没有多出边框线的滚动条滚动过快时留下边框线的问题通常与滚动条样式和滚动行

安装centos8设置基础软件仓库时出错的解决方案

《安装centos8设置基础软件仓库时出错的解决方案》:本文主要介绍安装centos8设置基础软件仓库时出错的解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录安装Centos8设置基础软件仓库时出错版本 8版本 8.2.200android4版本 javas

Python远程控制MySQL的完整指南

《Python远程控制MySQL的完整指南》MySQL是最流行的关系型数据库之一,Python通过多种方式可以与MySQL进行交互,下面小编就为大家详细介绍一下Python操作MySQL的常用方法和最... 目录1. 准备工作2. 连接mysql数据库使用mysql-connector使用PyMySQL3.