Custom Auto Imports in Nuxt 3 (Auto Import Pinia Store)
Asked Answered
A

2

6

Is there a way to set custom auto imports in Nuxt 3? I use Pinia and my stores are in the root directory under /stores. For example, if I want to use the store from /stores/auth.store.ts in a component, I always have to import the store like this:
import { useCourseStore } from '~~/stores/course.store';.

Aranda answered 23/3, 2023 at 13:53 Comment(0)
S
8

As defined on Pinia doc https://pinia.vuejs.org/ssr/nuxt.html#auto-imports, you can set this config in your nuxt.config.ts

export default defineNuxtConfig({
  // your config...
  modules: [
    [
      '@pinia/nuxt',
      { autoImports: ['defineStore'] },
    ],
  ],
});

And you can also define custom import dirs in your config https://nuxt.com/docs/api/configuration/nuxt-config#imports

export default defineNuxtConfig({
  // your config
  imports: {
    dirs: ['stores'],
  },
});
Sedative answered 23/3, 2023 at 17:0 Comment(2)
The Docs say "It also automatically imports all stores defined withing your stores folder." but my Store is not found out of the box 🤔Burschenschaft
Just me being curious (and also frustrated after couple of days tryna find reason why nuxt.config.ts > pinia > autoImports was not longer working after upgrading my nuxt version): How did you realize it had been moved to the modules apart? I haven't been able to find a trace of clue at the nuxt official docs.Gymnastic
N
1

Tristan's Answer pointed in the right direction, in the meantime the nuxt.config.ts syntax has changed a little:

// nuxt.config.ts
export default defineNuxtConfig({
  // ... other options
  modules: ['@pinia/nuxt'],
  pinia: {
    storesDirs: ['./stores/**', './custom-folder/stores/**'],
  },
})

Source: https://pinia.vuejs.org/ssr/nuxt.html#auto-imports

Namely answered 5/3 at 8:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.