feature-sliced / steiger Goto Github PK
View Code? Open in Web Editor NEWUniversal file structure and project architecture linter
Home Page: https://www.npmjs.com/package/steiger
License: MIT License
Universal file structure and project architecture linter
Home Page: https://www.npmjs.com/package/steiger
License: MIT License
Example of a project with the issue: https://github.com/feature-sliced/tutorial-conduit/tree/main
Sliced layers (Shared, Features, Widgets, Pages) should not have folders with conventional segment names in direct children.
Detect consistent naming of slices on layers (singular vs plural, casing)
entities/product
and entities/products
at the same time)Правило: no-reserved-folder-names.
Не совсем понятно что именно тут нарушается.
Sandbox: https://codesandbox.io/p/devbox/steiger-test-g4f4wp
Detect subfolders in segments that have names of common segments (e.g., shared/lib/ui)
Discourage file-segments (e.g., pages/home/ui.tsx)
Given a file name, an imported path, and a TSConfig object, produce an absolute path to the imported file.
Example (inside $PROJECT_FOLDER
):
// ./src/pages/home/ui/HomePage.tsx
import { Button } from "~/shared/ui";
// ./tsconfig.json
{
"include": ["**/*.ts", "**/*.tsx"],
"compilerOptions": {
"moduleResolution": "Bundler",
"baseUrl": ".",
"paths": {
"~/*": ["./src/*"],
},
},
}
Expected output: $PROJECT_FOLDER/src/shared/ui/index.ts
Detect slice names that match some segment’s name in shared (e.g., theme, i18n)
Imports within a slice should be relative, and imports between slices should be absolute
returns an error:
but the project has more than one necessary import, for example:
reproduced on windows 10
configuration used:
tsconfig.json
path of the file importing utilities from entities/conference:
src/widgets/messenger-chat\ui\ChatHeader\ConferenceMembersIndicator.tsx
Currently, the quality checks on different OSes fail, but the job succeeds anyway.
У нас на проекте нейминг сегментов использует в angular-like стиль:
cart.ui.tsx
cart.model.ts
cart.lib.ts
...
В некоторых местах где нет отдельных папок вроде 'ui', 'lib', и .тд. линтер ругается на то, что слайс без сегментов - что неверно.
Sandbox: https://codesandbox.io/p/devbox/steiger-test-g4f4wp
Detect index files on layer level
Detect small (by LoC) slices on entities/features/widgets that are only used on a single page and suggest moving them into the page
https://github.com/pijng/moonlogs/tree/master/web/src/widgets
✘ Repetitive word "schemas" in slice names on layer "widgets" // repetitive-naming
✘ Repetitive word "list" in slice names on layer "widgets" // repetitive-naming
Warn about too much stuff in shared/lib
Warn about repetitive parts in slice names (e.g. adding page to every slice on Pages)
Hey. I have a feature request: turn off a rule for specific folders/files by path. For example, we have some mocks (which located at an entity layer) and we deliberately don't add them to the public API to don't increase the bundle size.
✘ Forbidden sidestep of public API when importing "shared/lib/server/index.ts" from "widgets/ProductDetails/api/__mocks__/widgetProductDetailsHandlers.ts". // no-public-api-sidestep
✘ Forbidden sidestep of public API when importing "entities/product/api/__mocks__/mockProductDtoByIds.ts" from "widgets/BaseProductList/ui/BaseProductList.stories.tsx". // no-public-api-sidestep
It could look like this:
export default defineConfig({
rules: {
'no-public-api-sidestep': 'on',
},
overrides: [
{
// Maybe we should specify two types of groups ("when importing" files and "from" files)
// Allow import any file from `@/shared/lib/server/**/*.ts` from `**/__mocks__/**/*.ts`
patternFrom: ['**/__mocks__/**/*.ts']
patternTo: ['@/shared/lib/server/**/*.ts']
rules: {
'no-public-api-sidestep': 'off'
}
},
{
patternFrom: ['*.stories.tsx']
patternTo: ['**/__mocks__/**/*.ts']
rules: {
'no-public-api-sidestep': 'off'
}
}
]
})
Hey. I have a feature request: setup current rules from config file. For example, turn off some layers for "forbidden-import" rule.
✘ Forbidden cross-import on layer "entities" from "wishlist/model/slice.ts" to slice "product". // forbidden-imports
✘ Forbidden cross-import on layer "entities" from "wishlist/lib/mapWishlist.ts" to slice "product". // forbidden-imports
✘ Forbidden cross-import on layer "entities" from "wishlist/api/types.ts" to slice "product". // forbidden-imports
✘ Forbidden cross-import on layer "entities" from "wishlist/api/wishlistApi.ts" to slice "product". // forbidden-imports
✘ Forbidden cross-import on layer "entities" from "theme/lib/ThemeProvider.tsx" to slice "featureToggle". // forbidden-imports
✘ Forbidden cross-import on layer "entities" from "category/model/types.ts" to slice "product". // forbidden-imports
It could look like this:
export default defineConfig({
rules: {
'forbidden-imports': ['on', {
ignoreLayers: ['entities']
}],
},
})
Detect bad segment names (components, hooks, helpers, utils, modals)
Take some projects from FSD examples, pin a commit hash and run the linter on that commit. Then make fixes and run again to see the issues go away.
The test should run on all OSes on Node 18+
Hey. I have a feature request: I want to write rules for my project and i import them via config.
It could look like:
import { defineConfig } from 'steiger'
import rules from '...'
export default defineConfig({
preset: [...rules]
})
May be I'm doing something wrong, but I can't get an error about forbidden import hierarchy, e.g. when importing app
in entities
.
Here is the sandbox: https://codesandbox.io/p/devbox/steiger-test-g4f4wp
Restrict imports that go inside the slice, sidestepping the public API.
Every slice (and segment on layers that don't have slices) must contain a public API definition.
Modules outside of this slice/segment can only reference the public API, not the internal file structure of the slice/segment.
https://feature-sliced.design/docs/reference/slices-segments#public-api-rule-on-slices
Examples of imports that violate this rule:
// src/pages/home/ui/HomePage.tsx
import { ArticlePreview } from "~/entities/article/ui/ArticlePreview`;
Pay attention in designing this rule that some people choose to sidestep the public API in Shared, especially shared/ui
, to improve tree-shaking
Require slices (or segments on sliceless layers) to have a public API.
Every slice (and segment on layers that don't have slices) must contain a public API definition.
https://feature-sliced.design/docs/reference/slices-segments#public-api-rule-on-slices
Pay attention that some people prefer to have several entry points to shared/ui
to help with tree-shaking and some people also like having the public API on segments in sliced layers.
Привет! В eslint инструментах есть удобная фича перехода по ссылке на файл по подсвеченной проблеме. Очень бы хотелось видеть это в steiger, т.к. это значительно повышает DX.
Сейчас путь до файла в консоли есть, но активной ссылки на этот текст нет. Это вносит определенные неудобства.
Мы на проекте пришли к соглашению, что в слое виджетов мы разрешаем кросс-импорты в части композиции верстки (т.е. на уровне ui, а не моделей).
Было бы круто, если бы это можно было настроить в Steiger.
Restrict imports within a single FSD root that violates the import rule on layers:
A module in a slice can only import other slices when they are located on layers strictly below.
https://feature-sliced.design/docs/reference/layers#import-rule-on-layers
Discourage wildcard exports export * from
in public APIs.
Examples of code violating this rule:
// src/shared/ui/index.ts
export * from "./form";
Examples of code passing this rule:
// src/shared/ui/index.ts
export { Form, Field } from "./form";
export * as positions from "./tooltip-positions";
It would be nice to allow people to write custom rules in the lowest friction possible — by simply having rules in their project and linking them in the config file
Hey. I have a feature request: I want to see errors in warning mode (like in eslint). This will allow you to see errors, but not crash in CI.
It could look like:
export default defineConfig({
rules: {
'forbidden-imports': 'warn'
},
})
Планируется ли создание АПИ для внедрения собственных правил в линтинг?
Для улучшения DX хотелось бы видеть в Steiger поддержку в двух популярных IDE (JetBrains, VS Code).
Detect slices that don’t have segments
Как мы знаем shared слой состоит не из слайсов, а из сегментов. Требование Public API для сегментов shared слоя не кажется избыточным? Может вы не учли исключение shared слоя при написании этого правила?
Sandbox: https://codesandbox.io/p/devbox/steiger-test-g4f4wp
==================================================
Из этого вытекает вторая проблема: если в shared слое т.к. он состоит из сегментов убирать Public API - в линтере нужна настройка разрешенной глубины импортов для конкретного слоя, чтобы это не выглядело нарушением Public API, e.g.:
import from 'shared/ui/card'
Воспроизвести в сэндбоксе быстро не получилось.
Currently, if you pass no paths, the CLI fails, that's not great. Make it detect the most optimal place to run and notify that this is the folder that is used as the root
Сейчас имена сегментов захардкожены в линтере? И как я понимаю это правило не закастомизировать в данный момент: issue?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.