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

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

相关文章

Linux线程之线程的创建、属性、回收、退出、取消方式

《Linux线程之线程的创建、属性、回收、退出、取消方式》文章总结了线程管理核心知识:线程号唯一、创建方式、属性设置(如分离状态与栈大小)、回收机制(join/detach)、退出方法(返回/pthr... 目录1. 线程号2. 线程的创建3. 线程属性4. 线程的回收5. 线程的退出6. 线程的取消7.

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

java实现docker镜像上传到harbor仓库的方式

《java实现docker镜像上传到harbor仓库的方式》:本文主要介绍java实现docker镜像上传到harbor仓库的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 前 言2. 编写工具类2.1 引入依赖包2.2 使用当前服务器的docker环境推送镜像2.2

一文详解Git中分支本地和远程删除的方法

《一文详解Git中分支本地和远程删除的方法》在使用Git进行版本控制的过程中,我们会创建多个分支来进行不同功能的开发,这就容易涉及到如何正确地删除本地分支和远程分支,下面我们就来看看相关的实现方法吧... 目录技术背景实现步骤删除本地分支删除远程www.chinasem.cn分支同步删除信息到其他机器示例步骤

浏览器插件cursor实现自动注册、续杯的详细过程

《浏览器插件cursor实现自动注册、续杯的详细过程》Cursor简易注册助手脚本通过自动化邮箱填写和验证码获取流程,大大简化了Cursor的注册过程,它不仅提高了注册效率,还通过友好的用户界面和详细... 目录前言功能概述使用方法安装脚本使用流程邮箱输入页面验证码页面实战演示技术实现核心功能实现1. 随机

python如何创建等差数列

《python如何创建等差数列》:本文主要介绍python如何创建等差数列的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录python创建等差数列例题运行代码回车输出结果总结python创建等差数列import numpy as np x=int(in

前端如何通过nginx访问本地端口

《前端如何通过nginx访问本地端口》:本文主要介绍前端如何通过nginx访问本地端口的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、nginx安装1、下载(1)下载地址(2)系统选择(3)版本选择2、安装部署(1)解压(2)配置文件修改(3)启动(4)

怎么用idea创建一个SpringBoot项目

《怎么用idea创建一个SpringBoot项目》本文介绍了在IDEA中创建SpringBoot项目的步骤,包括环境准备(JDK1.8+、Maven3.2.5+)、使用SpringInitializr... 目录如何在idea中创建一个SpringBoot项目环境准备1.1打开IDEA,点击New新建一个项

如何使用Maven创建web目录结构

《如何使用Maven创建web目录结构》:本文主要介绍如何使用Maven创建web目录结构的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录创建web工程第一步第二步第三步第四步第五步第六步第七步总结创建web工程第一步js通过Maven骨架创pytho