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/ 目錄中找到的模組,它們按字母順序載入。

你可以透過在每個目錄名稱前新增數字來改變本地模組的順序

目錄結構
modules/
  1.first-module/
    index.ts
  2.second-module.ts
閱讀更多,請參見 文件 > 4 X > 指南 > 深入 > 模組
觀看 Vue School 關於 Nuxt 私有模組的影片。