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 { createResolver, defineNuxtModule, addServerHandler } from 'nuxt/kit'
export default defineNuxtModule({
meta: {
name: 'hello'
},
setup () {
const { resolve } = createResolver(import.meta.url)
// Add an API route
addServerHandler({
route: '/api/hello',
handler: resolve('./runtime/api-route')
})
}
})
當啟動 Nuxt 時,hello
模組將被註冊,且 /api/hello
路由將可用。
模組會依以下順序執行
- 首先,在
nuxt.config.ts
中定義的模組會被載入。 - 然後,在
modules/
目錄中找到的模組會被執行,並依字母順序載入。
您可以透過在每個目錄名稱前面新增數字來變更本地模組的順序
目錄結構
modules/
1.first-module/
index.ts
2.second-module.ts