javascriptnode.jsnuxt3.jsauto-importnitro

auto-import entire folder in nuxt 3 (server side)


I need to import all script files inside a server folder server/models

and i tried these inside nuxt.config file:

  nitro: {
    plugins: ['~/server/index.ts'],
    scanDirs: ['~/server/models']
  },
  imports: {
    dirs: [
      '~/server/models',
      // '~/server/models/**',
    ],
    global: true
  }

also defined modules like:

(options, nuxt) => {
      const { resolve } = createResolver(import.meta.url)
      addServerImportsDir(resolve('./server/models'))
      // nuxt.hooks.hook('nitro:config', (config) => {
      //   config.plugins = config.plugins || []
      //   config.plugins.push(resolve('server/models'))
      // })
}

but none of them imported exported model files automatically and globally for server codes


Solution

  • Since it is server-side, nest the imports inside nitro option. And do not use ~, but a relative route:

    export default defineNuxtConfig({
      nitro: {
        imports: {
          dirs: [
            './server/helpers'
          ]
        }
      }
    })
    

    Note, it is also possible to use /server/utils that gets autoimported out-of-the-box.