Skip to content

Korotkov-S/react-cli

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

34 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

KS REACT CLI

Зачем это нужно?

Стандартизация процессов и наличие готовых шаблонов компонентов позволяют значительно ускорить разработку и сопровождение React-приложений. CLI-утилита автоматически создаёт структуру файлов и кода по вашему стилю.

Быстрый старт

  1. Установите пакет:
npm i -D ks-react-cli-lib
  1. Добавьте скрипт в package.json:
{
  "scripts": {
    "cli-create": "ks-react-cli"
  }
}
  1. Запустите генератор:
npm run cli-create
  1. Следуйте инструкциям в терминале: выберите тип сущности и введите имя.

Поддерживаемые типы сущностей

  • Компонент (component)
  • Хук (hook)
  • Тип (type)
  • Хелпер (helper)
  • DTO (dto)
  • Сервис (service)
  • Иконка (icon)
  • Страница/экран (page/screen)
  • Контекст (context)

Каждый тип имеет свой шаблон и структуру файлов. Префиксы/суффиксы добавляются автоматически.

Кастомизация

  • Для расширения или переопределения типов сущностей создайте файл cli-config.cjs в корне проекта.
  • Можно изменить пути, шаблоны файлов, добавить свои типы сущностей.

Пример пользовательского конфига:

module.exports = {
  componentTypes: [
    {
      path: "./src/widgets",
      name: "widget",
      prefix: "",
      suffix: "Widget",
      files: (nameFile) => [
        {
          fileName: `${nameFile}.tsx`,
          template: `import React from "react";

export const ${nameFile} = () => {
  return <div>${nameFile}</div>;
};
`,
        },
        {
          fileName: `index.ts`,
          template: `export * from "./${nameFile}";
`,
        },
        // Можно добавить другие файлы по необходимости
      ],
    },
    // ...другие типы
  ],
};

Примеры шаблонов

Компонент:

import React from "react";
import style from "./Box.module.css";

export interface BoxProps {}

export const Box = ({}: BoxProps) => {
  return <div className={style.root}></div>;
};

Хук:

import React from "react";

export const useUser = () => {
  console.log("custom hook useUser");
};

Тип:

export type User = {};

Хелпер:

export class UserHelper {};

DTO:

export class UserDto {
  serialize<T>(): Record<string, T> {
    const dto: Record<string, T> = Object.assign(this);
    Object.keys(dto).forEach(key => {
      if (dto[key] === undefined) {
        delete dto[key];
      }
    });
    return dto;
  }
}

Сервис:

export class UserService {};

Иконка:

import React from "react";
interface IconArrowProps extends React.SVGProps<SVGSVGElement> {}

export const IconArrow = (props: IconArrowProps) => ();

Страница/экран:

import React from "react";
import style from "./MainScreen.module.css";

export interface MainScreenProps {}

export const MainScreen = ({}: MainScreenProps) => {
  return <div className={style.root}></div>;
};

Контекст:

import React from "react";
export type RootProviderProps = {
  children: React.ReactNode;
};

export const RootContext = React.createContext({});
export const RootProvider = ({children}: RootProviderProps) => (
  <RootContext.Provider value={{}}>
    {children}
  </RootContext.Provider>
);

Лицензия

Открытое ПО под лицензией MIT.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published