Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added usage with nuxt guide #679

Merged
merged 8 commits into from
Jun 16, 2024
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
---
sidebar_position: 10
---
# Usage 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 `src` directory

Add an `alias` object to your config:

```ts title="nuxt.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 the project, and create app and pages layers inside this directory and a routes folder inside the app layer.
Thus, your file structure should look like this:

```sh
├── src
│ ├── app
│ │ ├── routes
│ ├── 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:
falkomerr marked this conversation as resolved.
Show resolved Hide resolved
```ts title="nuxt.config.ts"
export default defineNuxtConfig({
devtools: { enabled: true }, // Not FSD related, enabled at project startup
alias: {
"@": '~/src'
},
dir: {
pages: './src/app/routes'
}
})
```

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 pages home
```

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

```ts title="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
│ │ ├── routes
│ │ │ ├── home
│ │ │ │ ├── index.vue
│ ├── pages
│ │ ├── home
│ │ │ ├── ui
│ │ │ │ ├── home-page.vue
│ │ │ ├── index.ts
```

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

```html title="pages/home/ui/home-page.vue"
<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 title="nuxt.config.ts"
export default defineNuxtConfig({
devtools: { enabled: true }, // Not related to FSD, enabled at project startup
alias: {
"@": '~/src'
},
dir: {
pages: './src/app/routes',
layouts: './src/app/layouts'
}
})
```


## 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)
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
---
sidebar_position: 10
---
# Использование с NuxtJS

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

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


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

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

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

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

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

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

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

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

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

```shell
fsd pages home
```

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

```ts title="src/pages/home/index.ts"
export { default as HomePage } from './ui/home-page';
```

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

```sh

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

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

```html title="pages/home/ui/home-page.vue"
<script setup>
import { HomePage } from '@/pages/home';
</script>

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

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

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

```ts title="nuxt.config.ts"
export default defineNuxtConfig({
devtools: { enabled: true }, // Не относятся к FSD, включёны при старте проекта
alias: {
"@": '~/src'
},
dir: {
pages: './src/app/routes',
layouts: './src/app/layouts'
}
})
```


## См. также

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