modules

使用 modules/ 目录在你的应用中自动注册本地模块。

这是放置在构建应用时开发的任何本地模块的好地方。

自动注册的文件模式为:

  • modules/*/index.ts
  • modules/*.ts

你不需要将这些本地模块单独添加到你的 nuxt.config.ts

// `nuxt/kit` is a helper subpath import you can use when defining local modules
// that means you do not need to add `@nuxt/kit` to your project's dependencies
import { addServerHandler, createResolver, defineNuxtModule } from 'nuxt/kit'

export default defineNuxtModule({
  meta: {
    name: 'hello',
  },
  setup () {
    const resolver = createResolver(import.meta.url)

    // Add an API route
    addServerHandler({
      route: '/api/hello',
      handler: resolver.resolve('./runtime/api-route'),
    })
  },
})

在启动 Nuxt 时,hello 模块将被注册,并且 /api/hello 路由将可用。

模块按以下顺序执行:

  • 首先,加载在 nuxt.config.ts 中定义的模块。
  • 然后,执行在 modules/ 目录中找到的模块,并按字母顺序加载。

你可以通过在每个目录名前添加数字来改变本地模块的加载顺序:

Directory structure
modules/
  1.first-module/
    index.ts
  2.second-module.ts
Read more in Docs > 4 X > Guide > Going Further > Modules.
观看关于 Nuxt 私有模块的 Vue School 视频。