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

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

相关文章

使用Python和Pyecharts创建交互式地图

《使用Python和Pyecharts创建交互式地图》在数据可视化领域,创建交互式地图是一种强大的方式,可以使受众能够以引人入胜且信息丰富的方式探索地理数据,下面我们看看如何使用Python和Pyec... 目录简介Pyecharts 简介创建上海地图代码说明运行结果总结简介在数据可视化领域,创建交互式地

解决Maven项目idea找不到本地仓库jar包问题以及使用mvn install:install-file

《解决Maven项目idea找不到本地仓库jar包问题以及使用mvninstall:install-file》:本文主要介绍解决Maven项目idea找不到本地仓库jar包问题以及使用mvnin... 目录Maven项目idea找不到本地仓库jar包以及使用mvn install:install-file基

Maven如何手动安装依赖到本地仓库

《Maven如何手动安装依赖到本地仓库》:本文主要介绍Maven如何手动安装依赖到本地仓库问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、下载依赖二、安装 JAR 文件到本地仓库三、验证安装四、在项目中使用该依赖1、注意事项2、额外提示总结一、下载依赖登

Android实现两台手机屏幕共享和远程控制功能

《Android实现两台手机屏幕共享和远程控制功能》在远程协助、在线教学、技术支持等多种场景下,实时获得另一部移动设备的屏幕画面,并对其进行操作,具有极高的应用价值,本项目旨在实现两台Android手... 目录一、项目概述二、相关知识2.1 MediaProjection API2.2 Socket 网络

HTML5中的Microdata与历史记录管理详解

《HTML5中的Microdata与历史记录管理详解》Microdata作为HTML5新增的一个特性,它允许开发者在HTML文档中添加更多的语义信息,以便于搜索引擎和浏览器更好地理解页面内容,本文将探... 目录html5中的Mijscrodata与历史记录管理背景简介html5中的Microdata使用M

html5的响应式布局的方法示例详解

《html5的响应式布局的方法示例详解》:本文主要介绍了HTML5中使用媒体查询和Flexbox进行响应式布局的方法,简要介绍了CSSGrid布局的基础知识和如何实现自动换行的网格布局,详细内容请阅读本文,希望能对你有所帮助... 一 使用媒体查询响应式布局        使用的参数@media这是常用的

HTML5表格语法格式详解

《HTML5表格语法格式详解》在HTML语法中,表格主要通过table、tr和td3个标签构成,本文通过实例代码讲解HTML5表格语法格式,感兴趣的朋友一起看看吧... 目录一、表格1.表格语法格式2.表格属性 3.例子二、不规则表格1.跨行2.跨列3.例子一、表格在html语法中,表格主要通过< tab

Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案

《Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案》:本文主要介绍Vue3组件中getCurrentInstance()获取App实例,但是返回nu... 目录vue3组件中getCurrentInstajavascriptnce()获取App实例,但是返回n

IDEA自动生成注释模板的配置教程

《IDEA自动生成注释模板的配置教程》本文介绍了如何在IntelliJIDEA中配置类和方法的注释模板,包括自动生成项目名称、包名、日期和时间等内容,以及如何定制参数和返回值的注释格式,需要的朋友可以... 目录项目场景配置方法类注释模板定义类开头的注释步骤类注释效果方法注释模板定义方法开头的注释步骤方法注

pytorch自动求梯度autograd的实现

《pytorch自动求梯度autograd的实现》autograd是一个自动微分引擎,它可以自动计算张量的梯度,本文主要介绍了pytorch自动求梯度autograd的实现,具有一定的参考价值,感兴趣... autograd是pytorch构建神经网络的核心。在 PyTorch 中,结合以下代码例子,当你