Skip to main content

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:

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:

โ”œโ”€โ”€ 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:

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:

fsd pages home

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

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

Create a root for this page inside the app layer:


โ”œโ”€โ”€ src
โ”‚ โ”œโ”€โ”€ app
โ”‚ โ”‚ โ”œโ”€โ”€ routes
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ index.vue
โ”‚ โ”œโ”€โ”€ pages
โ”‚ โ”‚ โ”œโ”€โ”€ home
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ ui
โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ home-page.vue
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ index.ts

Add your page component inside the index.vue file:

src/app/routes/index.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:

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โ€‹