Skip to content

Commit

Permalink
feat: added usage with nuxt guide
Browse files Browse the repository at this point in the history
  • Loading branch information
falkomerr committed Jun 10, 2024
1 parent 1a8bc29 commit 5edfa20
Show file tree
Hide file tree
Showing 2 changed files with 241 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
---
sidebar_position: 10
---
# Use with NuxtJS

It is possible to implement FSD in a NuxtJS project, but conflicts arise due to differences between the NuxtJS project structure requirements and FSD principles:

- Initially, NuxtJS offers a project file structure without a `src` folder, i.e. in the root of the project.
- The file routing is in the `pages` folder, while in FSD this folder is reserved for the flat slice structure.


## Adding an alias for the `rc` directory

Add an `alias` object to your config:

```ts
export default defineNuxtConfig({
devtools: { enabled: true }, // Not related to FSD, enabled at project startup
alias: {
"@": '~/src'
},
})
```

## Move file routing to `src/app`.

First of all, create a `src` directory in the root of your project, and create app and pages layers inside this directory.
Thus, your file structure should look like this:

```sh
├─── src
│ ├─── app
│ ├─── pages # The pages folder assigned to FSD
```

In order for NuxtJS to use the `app` layer for file routing, you need to modify `nuxt.config.ts` as follows:
```ts
export default defineNuxtConfig({
devtools: { enabled: true }, // Not FSD related, enabled at project startup
alias: {
"@": '~/src'
},
dir: {
pages: './src/app'
}
})
```

Now, you can create roots for pages within `app` and connect pages from `pages` to them.

For example, to add a `Home` page to your project, you need to do the following steps:
- Add a page slice inside the `pages` layer
- Add the corresponding root inside the `app` layer
- Align the page from the slice with the root

To create a page slice, let's use the [CLI](https://github.com/feature-sliced/cli):

```shell
fsd p home -s ui
```

Create a ``home-page.vue`` file inside the ui segment, access it using the Public API

```ts
// src/pages/home/index.ts

export { default as HomePage } from './ui/home-page';
```

Create a root for this page inside the `app` layer:

```sh

├─── src
│ ├─── app
│ │ ├───home
│ │ │ │ ├──── index.vue
│ ├─── pages
│ │ │ ├───home
│ │ │ │ ├──── ui
│ │ │ │ │ │ ├──── home-page.vue
│ │ │ │ ├──── index.ts

```

Add your page component inside the `index.vue` file:

```html
<script setup>
import { HomePage } from '@/pages/home';
</script>

<template>
<HomePage/>
</template>
```

## What to do with `layouts`?

You can place layouts inside the `app` layer, to do this you need to modify the config as follows:

```ts
export default defineNuxtConfig({
devtools: { enabled: true }, // Not related to FSD, enabled at project startup
alias: {
"@": '~/src'
},
dir: {
pages: './src/app',
layouts: './src/app/_layouts' // The underscore is needed to make it clear that layouts is not a page.
}
})
```


## See also

- [Documentation on changing directory config in NuxtJS](https://nuxt.com/docs/api/nuxt-config#dir)
- [Documentation on changing aliases in NuxtJS](https://nuxt.com/docs/api/nuxt-config#alias)

[project-knowledge]: /docs/about/understanding/knowledge-types
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
---
sidebar_position: 10
---
# Использование с NuxtJS

В NuxtJS проекте возможно реализовать FSD, однако возникают конфликты из-за различий между требованиями к структуре проекта NuxtJS и принципами FSD: 

- Изначально, NuxtJS предлагает файловую структуру проекта без папки `src`, то есть в корне проекта.
- Файловый роутинг находится в папке `pages`, а в FSD эта папка отведена под плоскую структуру слайсов.


## Добавление алиаса для `src` директории

Добавьте обьект `alias` в ваш конфиг:
```ts
export default defineNuxtConfig({
devtools: { enabled: true }, // Не относятся к FSD, включёны при старте проекта
alias: {
"@": '~/src'
},
})
```

## Перемещение файлового роутинга в `src/app`

В первую очередь, создайте `src` директорию в корне проекта, а также создайте внутри этой директории слои app и pages.
Таким образом, ваша файловая структура должна выглядеть так:

```sh
├── src
│ ├── app
│ ├── pages # Папка pages, закреплённая за FSD
```

Для того чтобы NuxtJS использовал слой `app` для файлового роутинга, вам нужно изменить `nuxt.config.ts` следующим образом:
```ts
export default defineNuxtConfig({
devtools: { enabled: true }, // Не относятся к FSD, включёны при старте проекта
alias: {
"@": '~/src'
},
dir: {
pages: './src/app'
}
})
```

Теперь, вы можете создавать роуты для страниц внутри `app` и подключать к ним страницы из `pages`.

Например, чтобы добавить страницу `Home` в проект, вам нужно сделать следующие шаги:
- Добавить слайс страницы внутри слоя `pages`
- Добавить соответствующий роут внутрь слоя `app`
- Совместить страницу из слайса с роутом

Для того чтобы создать слайс страницы, воспользуемся [CLI](https://github.com/feature-sliced/cli):

```shell
fsd p home -s ui
```

Создайте файл `home-page.vue` внутри сегмента ui, откройте к нему доступ с помощью Public API

```ts
// src/pages/home/index.ts

export { default as HomePage } from './ui/home-page';
```

Создайте роут для этой страницы внутри слоя `app`:

```sh

├── src
│ ├── app
│ │ ├──home
│ │ │ ├── index.vue
│ ├── pages
│ │ ├──home
│ │ │ ├── ui
│ │ │ │ ├── home-page.vue
│ │ │ ├── index.ts

```

Добавьте внутрь `index.vue` файла компонент вашей страницы:

```html
<script setup>
import { HomePage } from '@/pages/home';
</script>

<template>
<HomePage/>
</template>
```

## Что делать с `layouts`?

Вы можете разместить layouts внутри слоя `app`, для этого нужно изменить конфиг следующим образом:

```ts
export default defineNuxtConfig({
devtools: { enabled: true }, // Не относятся к FSD, включёны при старте проекта
alias: {
"@": '~/src'
},
dir: {
pages: './src/app',
layouts: './src/app/_layouts' // Нижнее подчеркивание нужно что-бы было понятно что layouts - не страница
}
})
```


## См. также

- [Документация по изменению конфига директорий в NuxtJS](https://nuxt.com/docs/api/nuxt-config#dir)
- [Документация по изменению алиасов в NuxtJS](https://nuxt.com/docs/api/nuxt-config#alias)

[project-knowledge]: /docs/about/understanding/knowledge-types

0 comments on commit 5edfa20

Please sign in to comment.