prettier-plugin-import-sections weekly downloads statistics
By pozib-hub · npm · Prettier plugins
Prettier plugin for automatic import sorting by sections (Api, Components, Constants, Helpers, Hooks, Types, Styles)
prettier-plugin-import-sections has 6 recorded weekly downloads on npm, a decrease of 25.0% over the past 30 days, ranking #3203 of 3,247 tracked listings.
About prettier-plugin-import-sections
prettier-plugin-import-sections
Prettier-плагин для автоматической сортировки импортов по секциям.
Плагин переиспользуемый — не содержит проект-специфичных хардкодов. Все настройки проекта задаются через .prettierrc или внешний конфиг-файл.
Быстрый старт
1. Установка
npm install --save-dev commission-prettier-plugin-import-sections prettier
2. Подключение в .prettierrc
{
"plugins": ["commission-prettier-plugin-import-sections"],
"importSectionsConfig": {
"componentHocs": ["typedMemo", "styled", "observer", "connect", "translate"],
"constantPrefixes": ["INITIAL_", "DEFAULT_", "TIME_", "TOOLBAR_"],
"constantSuffixes": ["_ROLES", "_ROUTES", "_COLUMNS", "_CONSTANTS", "_ALLOW_ROLES"],
"componentSuffixes": ["Page", "Modal", "Table", "Form", "Provider", "Context", "Button", "Input", "Field", "Card", "Section", "List", "Component"],
"helperFilenames": ["utils", "helpers", "util", "helper", "config", "setup"],
"knownTypeNames": ["Dispatch", "SetStateAction", "ReactNode", "ReactElement"]
}
}
2. Использование
# Prettier автоматически сортирует импорты при форматировании
npx prettier --write src/
# Или через npm-скрипт
npm run prettify
# CLI напрямую
npx sort-imports
# Dry-run (показать что изменится)
npx sort-imports --dry-run
# Конкретный файл
npx sort-imports src/uikit/Tooltip/Tooltip.tsx
Секции импортов
Импорты сортируются в следующем порядке:
//Api — данные и запросы к бэкенду
//Components — React-компоненты и UI-библиотеки
//Constants — статические значения, конфиги
//Helpers — утилиты и вспомогательные функции
//Hooks — React-хуки, react-hook-form, react-router
//Types — import type
//Styles — classnames/bind + SCSS-модуль (всегда последние)
Пример
//Api
import { useFetchCalcRulesParams } from 'api/points/universal/calcRules';
//Components
import { Button } from '@beeline/design-system-react';
import { SearchField } from 'uikit/SearchField';
//Constants
import { Icons } from 'shared/constants/icons';
//Helpers
import { clearFalsyProps } from 'shared/helpers/clearFalsyProps/clearFalsyProps';
//Hooks
import { useCallback, useState } from 'react';
import { useForm } from 'react-hook-form';
//Types
import type { ITableRow } from './types';
//Styles
import 'react-datepicker/dist/react-datepicker.css';
import cn from 'classnames/bind';
import styles from './index.module.scss';
const cx = cn.bind(styles);
Конфигурация (importSectionsConfig)
Все проект-специфичные настройки задаются через importSectionsConfig в .prettierrc:
| Ключ | Тип | Описание |
|---|---|---|
sectionOrder | string[] | Порядок секций (переупорядочивает дефолт) |
sectionAliases | object | Переименование секций ({"Api": "Backend"}) |
extraSections | object | Дополнительные секции с path-based правилами |
defaultSection | string | Дефолтная секция если ничего не совпало |
componentHocs | string[] | HOC-обёртки компонентов (typedMemo, styled, observer...) |
constantPrefixes | string[] | Префиксы констант (INITIAL_, DEFAULT_, TIME_...) |
constantSuffixes | string[] | Суффиксы констант (_ROLES, _COLUMNS, _CONSTANTS...) |
componentSuffixes | string[] | Суффиксы компонентов (Page, Modal, Table, Form...) |
helperFilenames | string[] | Имена файлов-утилит (utils, helpers, config...) |
knownTypeNames | string[] | Дополнительные имена типов (merges с автодетектом) |
projectAliases | object | Алиасы проекта (перезаписывает автодетект из tsconfig) |
apiPaths | string[] | Пути для секции Api |
helperPaths | string[] | Пути для секции Helpers |
componentPaths | string[] | Пути для секции Components |
constantsPaths | string[] | Пути для секции Constants |
uiLibraries | string[] | npm UI-библиотеки |
helperLibraries | string[] | npm утилиты |
Автодетект
Плагин автоматически определяет:
- PROJECT_ALIASES — из
tsconfig.jsoncompilerOptions.paths+ сканированиеsrc/ - API_PATHS, HELPER_PATHS, COMPONENT_PATHS, CONSTANTS_PATHS — по структуре
src/директорий - UI_LIBRARIES, HELPER_LIBRARIES — из
package.jsondependencies (react-* → UI, остальные → helpers) - KNOWN_TYPE_NAMES — из
@types/react,react-query,react-hook-form
Если значение задано в importSectionsConfig, оно merges с автодетектом (для knownTypeNames) или перезаписывает его (для остальных).
Конфигурируемые секции
Переименование секций
"sectionAliases": {
"Api": "Backend",
"Hooks": "React Hooks",
"Styles": "CSS"
}
Результат:
//Backend
import { useFetchData } from 'api/points/data';
//React Hooks
import { useCallback } from 'react';
//CSS
import cn from 'classnames/bind';
Порядок секций
"sectionOrder": ["Hooks", "Api", "Components", "Constants", "Helpers", "Types"]
Дополнительные секции
Можно добавить свои секции с path-based правилами:
"extraSections": {
"Redux": {
"paths": ["store/", "redux/"],
"comment": "Redux"
},
"i18n": {
"paths": ["locales/", "i18n/"],
"comment": "i18n"
}
}
Импорты из указанных путей попадут в новую секцию.
Дефолтная секция
"defaultSection": "Other"
Импорты, которые не совпали ни с одним правилом, попадут в указанную секцию.
Внешний конфиг-файл
Можно вынести конфиг в отдельный файл:
// .prettierrc
{
"plugins": ["commission-prettier-plugin-import-sections"],
"importSectionsConfig": "./import-sections.config.json"
}
// import-sections.config.json
{
"componentHocs": ["typedMemo", "styled"],
"constantPrefixes": ["INITIAL_"]
}
Определение секции
Скрипт определяет секцию импорта по правилам (приоритет сверху вниз):
1. Явные указатели…
Description from the npm listing.
- prettier
- prettier-plugin
- import-sorting
- import-sections
- import-order
- code-formatting
- react
- typescript
- eslint-plugin-import
README badge
Show your rank in a README or on your website. The badge updates automatically.
Charts
Images: 30d · 1y · all time · 1600×900 dark
Adoption over time
7/30/90-day growth
Ranking history
Listing placement
Listing placement
Filled points are observed values; hollow points come from Internet Archive snapshots of the listing page. Dashed segments span periods with no observations — values between points are not interpolated.
Each band is one page of 20. Weekly downloads on a linear scale. Placement is projected from weekly downloads, so it can differ from the marketplace's own sort order. Hover a dot to see the listing.
Recent observations
Full history (170)Similar npm Prettier plugins plugins
All 20 prettier-plugin-import-sections alternativesData source
Weekly downloads (trailing 7 complete days) come from the official npm downloads API. Downloads include CI and mirrors and are not equivalent to installs or users. npm publishes no ratings.
Listing: https://www.npmjs.com/package/prettier-plugin-import-sections. First seen Oct 16, 2026; last successful collection Dec 6, 2026. See the methodology.