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 config routing to nuxtjs guide #710

Merged
merged 2 commits into from
Aug 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ 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:
It is possible to implement FSD in a NuxtJS project, but conflicts arise due to the differences between 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.
Expand All @@ -12,32 +12,92 @@ It is possible to implement FSD in a NuxtJS project, but conflicts arise due to
## 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
devtools: { enabled: true }, // Not FSD related, enabled at project startup
alias: {
"@": '../src'
},
})
```
## Choose how to configure the router

In NuxtJS, there are two ways to customize the routing - using a config and using a file structure.
In the case of file-based routing, you will create index.vue files in folders inside the app/routes directory, and in the case of configure, you will configure the routers in the `router.options.ts` file.


### Routing using config

In the `app` layer, create a `router.options.ts` file, and export a config object from it:
```ts title="app/router.options.ts"
import type { RouterConfig } from '@nuxt/schema';

export default <RouterConfig> {
routes: (_routes) => [],
};

```

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 appropriate route to the `app/router.config.ts` config


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

```shell
fsd pages home
```

## Move file routing to `src/app`
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';
```

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, the file structure will look like this:
```sh
|── src
│ ├── app
│ │ ├── router.config.ts
│ ├── pages
│ │ ├── home
│ │ │ ├── ui
│ │ │ │ ├── home-page.vue
│ │ │ ├── index.ts
```
Finally, let's add a root to the config:

```ts title="app/router.config.ts"
import type { RouterConfig } from '@nuxt/schema'

export default <RouterConfig> {
routes: (_routes) => [
{
name: 'home',
path: '/',
component: () => import('@/pages/home.vue').then(r => r.default || r)
}
],
}
```

### File Routing

First of all, create a `src` directory in the root of your 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
│ ├── pages # Pages folder, related to FSD
```

In order for NuxtJS to use the `app` layer for file routing, you need to modify `nuxt.config.ts` as follows:
In order for NuxtJS to use the routes folder inside the `app` layer for file routing, you need to modify `nuxt.config.ts` as follows:
```ts title="nuxt.config.ts"
export default defineNuxtConfig({
devtools: { enabled: true }, // Not FSD related, enabled at project startup
devtools: { enabled: true }, // Not FSD related, enabled at project startup
alias: {
"@": '../src'
},
Expand All @@ -47,7 +107,7 @@ export default defineNuxtConfig({
})
```

Now, you can create roots for pages within `app` and connect pages from `pages` to them.
Now, you can create routes 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
Expand Down Expand Up @@ -99,7 +159,7 @@ You can place layouts inside the `app` layer, to do this you need to modify the

```ts title="nuxt.config.ts"
export default defineNuxtConfig({
devtools: { enabled: true }, // Not related to FSD, enabled at project startup
devtools: { enabled: true }, // Not related to FSD, enabled at project startup
alias: {
"@": '../src'
},
Expand All @@ -114,4 +174,6 @@ export default defineNuxtConfig({
## See also

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

Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ sidebar_position: 10
---
# Использование с NuxtJS

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

- Изначально, NuxtJS предлагает файловую структуру проекта без папки `src`, то есть в корне проекта.
- Файловый роутинг находится в папке `pages`, а в FSD эта папка отведена под плоскую структуру слайсов.
Expand All @@ -20,8 +20,69 @@ export default defineNuxtConfig({
},
})
```
## Выбор способа настройки роутера

## Перемещение файлового роутинга в `src/app`
В NuxtJS есть два способа настройки роутинга - с помощью конфига и с помощью файловой структуры.
В случае с файловым роутингом вы будете создавать index.vue файлы в папках внутри директории app/routes, а в случае конфига - настраивать роуты в `router.options.ts` файле.


### Роутинг с помощью конфига

В слое `app` создайте файл `router.options.ts`, и экспортируйте из него обьект конфига:
```ts title="app/router.options.ts"
import type { RouterConfig } from '@nuxt/schema';

export default <RouterConfig> {
routes: (_routes) => [],
};

```

Чтобы добавить страницу `Home` в проект, вам нужно сделать следующие шаги:
- Добавить слайс страницы внутри слоя `pages`
- Добавить соответствующий роут в конфиг `app/router.config.ts`


Для того чтобы создать слайс страницы, воспользуемся [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';
```

Таким образом, файловая структура будет выглядеть так:
```sh
|── src
│ ├── app
│ │ ├── router.config.ts
│ ├── pages
│ │ ├── home
│ │ │ ├── ui
│ │ │ │ ├── home-page.vue
│ │ │ ├── index.ts
```
Наконец, добавим роут в конфиг:

```ts title="app/router.config.ts"
import type { RouterConfig } from '@nuxt/schema'

export default <RouterConfig> {
routes: (_routes) => [
{
name: 'home',
path: '/',
component: () => import('@/pages/home.vue').then(r => r.default || r)
}
],
}
```

### Файловый роутинг

В первую очередь, создайте `src` директорию в корне проекта, а также создайте внутри этой директории слои app и pages и папку routes внутри слоя app.
Таким образом, ваша файловая структура должна выглядеть так:
Expand Down Expand Up @@ -113,4 +174,6 @@ export default defineNuxtConfig({
## См. также

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

2 changes: 1 addition & 1 deletion src/entities/example/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useCallback } from "react";
import React from "react";
import clsx from "clsx";
import Image from "@theme/IdealImage";
import { date } from "@site/src/shared/lib/date";
Expand Down
5 changes: 3 additions & 2 deletions src/pages/examples/_config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -416,13 +416,14 @@ export const examples: Example[] = [
},
{
title: "Tiny Bunny Mini Game",
description: "Mini-game \"21 points\" in the universe of the visual novel \"Tiny Bunny\".",
description:
'Mini-game "21 points" in the universe of the visual novel "Tiny Bunny".',
source: "https://github.com/sanua356/tiny-bunny",
website: "https://sanua356.github.io/tiny-bunny/",
preview: require("./img/tiny-bunny.png"),
version: VERSIONS.V2,
updatedAt: "2024-08-10",
tech: ["react", "redux-toolkit", 'typescript'],
tech: ["react", "redux-toolkit", "typescript"],
},
// Reverse the list (last examples should be at the top)
].reverse();