---
title: "modules"
description: "使用 modules/ 目录在你的应用中自动注册本地模块。"
canonical_url: "https://nuxt.zhcndoc.com/docs/4.x/directory-structure/modules"
---
# modules

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

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

自动注册的文件模式为：

- `modules/*/index.ts`
- `modules/*.ts`

你不需要在 [`nuxt.config.ts`](https://nuxt.zhcndoc.com/docs/4.x/directory-structure/nuxt-config) 中单独添加这些本地模块。

::code-group
```ts twoslash [modules/hello/index.ts]
// `nuxt/kit` 是一个定义本地模块时可以使用的辅助子路径导入
// 这意味着你不需要将 `@nuxt/kit` 添加到你的项目依赖中
import { addComponentsDir, addServerHandler, createResolver, defineNuxtModule } from 'nuxt/kit'

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

    // 添加一个 API 路由
    addServerHandler({
      route: '/api/hello',
      handler: resolver.resolve('./runtime/api-route'),
    })

    // 添加组件
    addComponentsDir({
      path: resolver.resolve('./runtime/app/components'),
      pathPrefix: true, // 给你的导出添加前缀以避免与用户代码或其他模块冲突
    })
  },
})
```

```ts twoslash [modules/hello/runtime/api-route.ts]
export default defineEventHandler(() => {
  return { hello: 'world' }
})
```
::

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

::note
请注意，所有通常放置在你的 `app/` 目录中的组件、页面、组合式函数和其他文件都需要放在 `modules/your-module/runtime/app/` 中。这样可以确保它们得到正确的类型检查。
::

模块按以下顺序执行：

- 首先，加载在 [`nuxt.config.ts`](https://nuxt.zhcndoc.com/docs/4.x/api/nuxt-config#modules-1) 中定义的模块。
- 然后，执行 `modules/` 目录中的模块，并按字母顺序加载。

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

```bash [目录结构]
modules/
  1.first-module/
    index.ts
  2.second-module.ts
```

::read-more{to="https://nuxt.zhcndoc.com/docs/4.x/guide/modules"}
::

::tip{icon="i-lucide-video" to="https://vueschool.io/lessons/creating-your-first-module-from-scratch?friend=nuxt" target="_blank"}
观看关于 Nuxt 私有模块的 Vue School 视频。
::


## Sitemap

See the full [sitemap](https://nuxt.zhcndoc.com/sitemap.md) for all pages.
