Search code examples
vue.jsnuxt.jspinia

How to auto import pinia stores in nuxt


Currently I am doing something like this to import stores in components

import { useSomeStore } from "~/store/someStore";
const store = useSomeStore();

What I would like to achieve is skip the import and just use the store

What I have done is add

// nuxt.config.ts
modules: [
  [
    "@pinia/nuxt",
    {
      autoImports: ["defineStore", "acceptHMRUpdate"],
    },
  ],
],
imports: {
  dirs: ["stores"],
},

in my nuxt config but I'm still getting useSomeStore is undefined, what am I doing wrong in this case?

The store:

// store/someStore.ts
export const useSomeStore = defineStore("some-store", {
  state: () => ({ hello: "there" }),
});

Solution

  • It looks like a typo to me. Your component import references location /store

    import { useSomeStore } from "~/store/someStore";
    

    but your config references /stores

    imports: {
      dirs: ['stores']
    }
    

    so is your store folder called /store or /stores?

    Assuming the former, your nuxt config should be:

    export default defineNuxtConfig({
      modules: [
        [
          "@pinia/nuxt",
          {
            autoImports: ["defineStore", "acceptHMRUpdate"],
          },
        ],
      ],
      imports: {
        dirs: ['store']
      }
    });