diff --git a/i18n/en/docusaurus-plugin-content-docs/current/guides/tech/with-nextjs.mdx b/i18n/en/docusaurus-plugin-content-docs/current/guides/tech/with-nextjs.mdx index a30b16912..9ae37087f 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/guides/tech/with-nextjs.mdx +++ b/i18n/en/docusaurus-plugin-content-docs/current/guides/tech/with-nextjs.mdx @@ -1,121 +1,118 @@ --- sidebar_position: 10 --- -# Usage with NextJS +# Usage with Next.js -It is possible to implement FSD in a NextJS project, but conflicts arise due to differences between the requirements for the NextJS project structure and the principles of FSD in two points:  +It's possible to implement FSD in a Next.js project, but conflicts arise due to differences between Next.js project structure requirements and FSD principles. -- Routing files in the `pages` layer -- Conflict or absence of the `app` layer in NextJS +## Conflict between FSD and Next.js in the `app` layer -## Conflict between FSD and NextJS on `pages` layer {#pages-conflict} +Next.js suggests using the `app` folder to define application routes. It expects files in the `app` folder to correspond to pathnames. +This routing mechanism **does not align** with the FSD concept, as it's not possible to maintain a flat slice structure with such a routing mechanism. +The approach is to move the Next.js `app` folder to the project root and import FSD pages into the Next.js `app` folder. +This preserves the FSD project structure inside the `src` folder, where layer folders should be placed. -NextJS suggests using the `pages` folder to define application routes. NextJS expects files in the `pages` folder to match URLs. -This routing mechanism **does not correspond** to the FSD concept, since it is not possible to maintain a flat slice structure in such a routing mechanism. - -### Moving the `pages` folder of NextJS to the root folder of the project (recommended) - -The approach is to move the `pages` NextJS folder to the root folder of the project and import the FSD pages into the `pages` NextJS folder. This saves -the FSD project structure inside the `src` folder. +You should also add a `pages` folder to the project root because App Router is compatible with Pages Router. +The best way is to put `README.md` file inside describing the need to save this folder. ```sh -├── pages # NextJS pages folder -├── src -│ ├── app -│ ├── entities -│ ├── features -│ ├── pages # FSD pages folder -│ ├── shared -│ ├── widgets +├── app # App folder (Next.js) + ├── api + │ └── get-example + │ └── route.ts +│ └── example +│ └── page.tsx +├── pages # Legacy pages folder (Next.js) +│ └── README.md # To maintain compatibility with Pages Router +└── src + ├── app + ├── pages + │ └── example + │ ├── index.ts + │ ├── ui + │ │ └── example.tsx + │ └── routes + │ └── get-example.ts # Route handler + ├── widgets + ├── features + ├── entities + └── shared ``` -### Renaming the `pages` layer within the FSD structure +### Example of re-exporting a page from `src/pages/example` to `app/example/page.tsx` -Another way to solve the problem is to rename the `pages` layer in the FSD structure to avoid conflicts with the NextJS `pages` folder. -You can rename the `pages` layer in FSD to `views`. -In that way, the structure of the project in the `src` folder is preserved without contradiction with the requirements of NextJS. - -```sh -├── app -├── entities -├── features -├── pages # NextJS pages folder -├── views # Renamed FSD pages folder -├── shared -├── widgets +```tsx title="app/example/page.tsx" +export { Example as default, metadata } from '@/pages/example'; ``` -Keep in mind that it's highly recommended to document this rename prominently in your project's README or internal documentation. This rename is a part of your ["project knowledge"][project-knowledge]. - -## The absence of the `app` folder in NextJS {#app-absence} - -In NextJS below version 13, there is no explicit `app` folder, instead NextJS provides the `_app.tsx` file, -which plays the role of a wrapping component for all project pages. - -### Importing app functionality to `pages/_app.tsx` file +### Middleware +If you use middleware in your project, it must be located in the project root alongside the `app` and `pages` folders. -To solve the problem of missing the `app` folder in the NextJS structure, you can create an `App` component inside the `app` layer and import the `App` component into `pages/_app.tsx` so that NextJS can work with it. -For example: +### Instrumentation +The `instrumentation.ts|js` file allows you to monitor the performance and behavior of your application. If you use it, it must be located in the project root, similar to `middleware.ts|js`. -```tsx -// app/providers/index.tsx +### Route Handlers +It is suggested to use a new `routes` segment in the `app` or `pages` layer to work with Route Handlers. -const App = ({ Component, pageProps }: AppProps) => { - return ( - - - - - - - - ); -}; - -export default App; +```tsx title="app/routes/get-example/route.ts" +export { getExample as GET } from '@/pages/example'; ``` -Then you can import the `App` component and global project styles into `pages/_app.tsx` as follows: -```tsx -// pages/_app.tsx +### Additional recommendations +- Use the `api` segment in the `shared` layer to describe database queries and their further use in higher layers. +- Caching and revalidating queries logic is better kept in the same place as the queries themselves, in a basic scenario this is the `api` segment in the `shared` layer. -import 'app/styles/index.scss' +## Legacy approach with Pages Router +Page routers should be placed in the `pages` folder in the root of the project, similar to `app` for the App Router. +The structure inside `src` where the layer folders are located remains unchanged. -export { default } from 'app/providers'; +```sh +├── pages # Pages folder (Next.js) +│ ├── _app.tsx +│ ├── api +│ │ └── example.ts # API Route re-export +│ └── example +│ └── index.tsx +└── src + ├── app + ├── pages + │ └── example + │ ├── index.ts + │ ├── ui + │ │ └── example.tsx + │ └── routes + │ ├── config.ts # API Route config + │ └── handler.ts # API Route + ├── widgets + ├── features + ├── entities + └── shared ``` -## Dealing with App Router {#app-router} +### Functionality re-export from the public API `src/app/index.ts` to `pages/_app.tsx` -App Router has become stable in NextJS version 13.4. App Router allows you to use the `app` folder for routing instead of the `pages` folder. -To comply with the principles of FSD, you should treat the NextJS `app` folder in the same way as recommended -to resolve a conflict with the NextJS `pages` folder. +```tsx title="pages/_app.tsx" +export { App as default } from '@/app'; +``` -The approach is to move the NextJS `app` folder to the root folder of the project and import the FSD pages into the NextJS `app` folder. This saves -the FSD project structure inside the `src` folder. You should still also add the `pages` folder to the root, because the App router is compatible with the Pages router. +### Example of re-exporting a page from `src/pages/example` to `pages/example/index.tsx` +```tsx title="pages/example/index.tsx" +export { Example as default } from '@/pages/example'; ``` -├── app # NextJS app folder -├── pages # Stub NextJS pages folder -│ ├── README.md # Description of why this folder exists -├── src -│ ├── app # FSD app folder -│ ├── entities -│ ├── features -│ ├── pages # FSD pages folder -│ ├── shared -│ ├── widgets -``` - -[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)][ext-app-router-stackblitz] -## Middleware +### API Routes +It is suggested to use a new `routes` segment in the `app` or `pages` layer to work with API Routes. -If you are using middleware in a project, it also needs to be moved from `src` to the root of the project. Otherwise, NextJS simply won't see it — middleware must be located strictly at the root next to `app` or `pages`. +```tsx title="app/api/example.ts" +export { handler as default, config } from '@/pages/example'; +``` -## See also {#see-also} +## See also -- [(Thread) About the pages directory in NextJS](https://t.me/feature_sliced/3623) +[Next.js Project Structure](https://Next.js.org/docs/app/getting-started/project-structure) +[Next.js Page Layouts](https://Next.js.org/docs/app/getting-started/layouts-and-pages) [project-knowledge]: /docs/about/understanding/knowledge-types -[ext-app-router-stackblitz]: https://stackblitz.com/edit/stackblitz-starters-aiez55?file=README.md +[ext-app-router-stackblitz]: https://stackblitz.com/edit/stackblitz-starters-aiez55?file=README.md \ No newline at end of file diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/tech/with-nextjs.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/guides/tech/with-nextjs.mdx index b4778fa09..82d222138 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/guides/tech/with-nextjs.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/tech/with-nextjs.mdx @@ -1,120 +1,118 @@ --- sidebar_position: 10 --- -# Использование с NextJS +# Использование с Next.js -В NextJS проекте возможно реализовать FSD, но возникают конфликты из-за различий между требованиями к структуре проекта NextJS и принципами FSD в двух пунктах:  +В Next.js проекте возможно реализовать FSD, но возникают конфликты из-за различий между требованиями к структуре проекта Next.js и принципами FSD. -- Маршрутизация файлов в слое `pages` -- Конфликт или отсутствие слоя `app` в NextJS +## Конфликт между FSD и Next.js в слое `app` -## Конфликт между FSD и NextJS в слое `pages` {#pages-conflict} - -NextJS предлагает использовать папку `pages` для определения маршрутов приложения. NextJS ожидает, что файлы в папке `pages` будут соответствовать URL-адресам. +Next.js предлагает использовать папку `app` для определения маршрутов приложения. Next.js ожидает, что файлы в папке `app` будут соответствовать URL-адресам. Этот механизм маршрутизации **не соответствует** концепции FSD, поскольку в таком механизме маршрутизации не представляется возможным соблюсти плоскую структуру слайсов. -### Перемещение папки `pages` NextJS в корневую папку проекта (рекомендуется) +Подход заключается в перемещении папки `app` Next.js в корневую папку проекта и импорте страниц FSD в папку `app` Next.js. +Это сохраняет структуру проекта FSD внутри папки `src`, где должны размещаться слои. -Подход заключается в перемещении папки `pages` NextJS в корневую папку проекта и импорте страниц FSD в папку `pages` NextJS. Это сохраняет -структуру проекта FSD внутри папки `src`. +Вам также стоит добавить в корневую папку проекта папку `pages`, потому что App Router совместим с Pages Router. +Лучшим способом будет положить внутрь `README.md` с описанием необходимости сохранить данную папку. ```sh -├── pages # Папка pages (NextJS) -├── src -│ ├── app -│ ├── entities -│ ├── features -│ ├── pages # Папка pages (FSD) -│ ├── shared -│ ├── widgets +├── app # Папка app (Next.js) + ├── api + │ └── get-example + │ └── route.ts +│ └── example +│ └── page.tsx +├── pages # Устаревшая папка pages (Next.js) +│ └── README.md # Для сохранения совместимости с Pages Router +└── src + ├── app + ├── pages + │ └── example + │ ├── index.ts + │ ├── ui + │ │ └── example.tsx + │ └── routes + │ └── get-example.ts # Route handler + ├── widgets + ├── features + ├── entities + └── shared ``` -### Переименование папки `pages` в структуре FSD - -Другой способ решить проблему - переименовать слой `pages` в структуре FSD, чтобы избежать конфликтов с папкой `pages` NextJS. -Вы можете переименовать слой `pages` в FSD в `views`.  -Таким образом, структура проекта в папке `src` сохраняется без противоречий с требованиями NextJS. +### Пример ре-экспорта страницы из `src/pages/example` в `app/example/page.tsx` -```sh -├── app -├── entities -├── features -├── pages # Папка pages (NextJS) -├── views # Переименованная папка страниц FSD -├── shared -├── widgets +```tsx title="app/example/page.tsx" +export { Example as default, metadata } from '@/pages/example'; ``` -Учтите, что в этом случае рекомендуется задокументировать это переименование в видном месте — в README проекта или внутренней документации. Это переименование — часть ["проектных знаний"][project-knowledge]. - -## Отсутствие папки `app` в NextJS {#app-absence} - -В NextJS ниже версии 13 нет явной папки `app`, вместо этого NextJS предоставляет файл `_app.tsx`, -который играет роль компонента обертывания для всех страниц проекта. - -### Импорт функциональности в `pages/_app.tsx` +### Middleware +Если вы используете middleware в проекте, он обязательно должен располагаться в корне проекта рядом с папками `app` и `pages`. -Чтобы решить проблему отсутствия папки `app` в структуре NextJS, вы можете создать компонент `App` внутри слоя `app` и импортировать компонент `App` в `pages/_app.tsx`, чтобы NextJS мог с ним работать. -Например: +### Instrumentation +Файл `instrumentation.ts|js` позволяет отслеживать производительность и поведение вашего приложения. Если вы его используете, то он обязательно должен находиться в корне проекта по аналогии с `middleware.ts|js` -```tsx -// app/providers/index.tsx +### Route Handlers +Предлагается использовать новый сегмент `routes` в слое `app` или `pages` для работы c Route Handlers. -const App = ({ Component, pageProps }: AppProps) => { - return ( - - - - - - - - ); -}; - -export default App; +```tsx title="app/api/get-example/route.ts" +export { getExample as GET } from '@/pages/example'; ``` -Затем вы можете импортировать компонент `App` и глобальные стили проекта в `pages/_app.tsx` следующим образом: -```tsx -// pages/_app.tsx +### Дополнительные рекомендации +- Используйте сегмент `api` в слое `shared` для описания запросов к БД и их дальнейшего использования в вышестоящих слоях. +- Логику кэширования и ревалидации запросов лучше держать там же, где и сами запросы, в базовом сценарии это сегмент `api` в слое `shared`. -import 'app/styles/index.scss' +## Устаревший подход с Pages Router +Роуты страниц должны помещаться в папку `pages` в корне проекта по аналогии с `app` для App Router. +Структура внутри `src`, где располагаются папки слоёв остаётся без изменений. -export { default } from 'app/providers'; +```sh +├── pages # Папка pages (Next.js) +│ ├── _app.tsx +│ ├── api +│ │ └── example.ts # API Route ре-экспорт +│ └── example +│ └── index.tsx +└── src + ├── app + ├── pages + │ └── example + │ ├── index.ts + │ ├── ui + │ │ └── example.tsx + │ └── routes + │ ├── config.ts # Конфигурация API Rout'а + │ └── handler.ts # API Route + ├── widgets + ├── features + ├── entities + └── shared ``` -## Работа с App Router {#app-router} +### Ре-экспорт функциональности в `pages/_app.tsx` из публичного API `src/app/index.ts` -App Router стал стабильным в NextJS версии 13.4. App Router позволяет использовать папку `app` для маршрутизации вместо папки `pages`. -Для соответствия принципам FSD, вам следует обращаться с папкой `app` NextJS так же, как рекомендуется -для устранения конфликта с папкой `pages` NextJS. +```tsx title="pages/_app.tsx" +export { App as default } from '@/app'; +``` -Подход заключается в перемещении папки `app` NextJS в корневую папку проекта и импорте страниц FSD в папку `app` NextJS. Это сохраняет -структуру проекта FSD внутри папки `src`. Вам также стоит добавить в корневую папку проекта папку `pages`, потому что App Router совместим с Pages Router. +### Пример ре-экспорта страницы из `src/pages/example` в `pages/example/index.tsx` +```tsx title="pages/example/index.tsx" +export { Example as default } from '@/pages/example'; ``` -├── app # Папка app (NextJS) -├── pages # Пустая папка pages (NextJS) -│ ├── README.md # Описание того, зачем нужна эта папка -├── src -│ ├── app # Папка app (FSD) -│ ├── entities -│ ├── features -│ ├── pages # Папка pages (FSD) -│ ├── shared -│ ├── widgets -``` - -[![Открыть в StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)][ext-app-router-stackblitz] -## Middleware +### API Routes +Предлагается использовать новый сегмент `routes` в слое `app` или `pages` для работы c API Routes. -Если вы используете middleware в проекте, его также нужно переместить из `src` в корень проекта. Иначе NextJS просто не увидит его — middleware должен находиться строго в корне рядом с `app` или `pages`. +```tsx title="app/api/example.ts" +export { handler as default, config } from '@/pages/example'; +``` -## См. также {#see-also} +## См. также -- [(Тред) Про pages директорию в NextJS](https://t.me/feature_sliced/3623) +[Структура проекта Next.js](https://Next.js.org/docs/app/getting-started/project-structure) +[Компоновка страниц Next.js](https://Next.js.org/docs/app/getting-started/layouts-and-pages) [project-knowledge]: /docs/about/understanding/knowledge-types -[ext-app-router-stackblitz]: https://stackblitz.com/edit/stackblitz-starters-aiez55?file=README.md +[ext-app-router-stackblitz]: https://stackblitz.com/edit/stackblitz-starters-aiez55?file=README.md \ No newline at end of file