---
title: "模块依赖"
description: "声明对其他模块的依赖，并支持版本约束和配置合并。"
canonical_url: "https://nuxt.zhcndoc.com/docs/4.x/guide/modules/module-dependencies"
---
# 模块依赖

> 声明对其他模块的依赖，并支持版本约束和配置合并。

如果你的模块依赖于其他模块，你可以使用 `moduleDependencies` 选项来声明它们。Nuxt 随后会确保这些模块按正确顺序安装，验证你提供的任何版本约束，并合并你为它们提供的配置。

## 基本用法

```ts
import { createResolver, defineNuxtModule } from '@nuxt/kit'

const resolver = createResolver(import.meta.url)

export default defineNuxtModule<ModuleOptions>({
  meta: {
    name: 'my-module',
  },
  moduleDependencies: {
    '@nuxtjs/tailwindcss': {
      // 你可以为该模块指定版本约束
      version: '>=6',
      // 任何应覆盖 `nuxt.options` 的配置
      overrides: {
        exposeConfig: true,
      },
      // 任何应被设置的配置。它会覆盖模块默认值，但
      // 不会覆盖 `nuxt.options` 中设置的任何配置
      defaults: {
        config: {
          darkMode: 'class',
          content: {
            files: [
              resolver.resolve('./runtime/components/**/*.{vue,mjs,ts}'),
              resolver.resolve('./runtime/*.{mjs,js,ts}'),
            ],
          },
        },
      },
    },
  },
  setup (options, nuxt) {
    // 我们可以注入包含 Tailwind 指令的 CSS 文件
    nuxt.options.css.push(resolver.resolve('./runtime/assets/styles.css'))
  },
})
```

::callout{type="info"}
`moduleDependencies` 选项取代了已弃用的 `installModule` 函数。
::

每个条目的键用于标识所依赖的模块。你可以使用 npm 包名、本地模块目录的路径，或者像 `~` 或 `@` 这样的 Nuxt 别名。

## 依赖本地模块

当依赖位于 [`modules/` 目录](https://nuxt.zhcndoc.com/docs/4.x/directory-structure/modules) 中时，使用文件路径声明依赖：

```ts
import { defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  moduleDependencies: {
    // 相对于项目根目录的路径
    './modules/my-local-module': {},
    // 或使用 Nuxt 别名
    '~/modules/another-local-module': {},
  },
  // ...
})
```

::important
**相对路径是从你项目的 `rootDir` 解析的**，而不是从声明依赖的文件位置解析。位于 `modules/foo.ts` 的模块引用 `modules/bar.ts` 时，必须使用 `'./modules/bar'`，而不是 `'./bar'`。使用诸如 `~/modules/bar` 的 Nuxt 别名可以避免这种歧义。
::

## 选项

`moduleDependencies` 中的每个条目都接受以下字段：

- `version`：一个 semver 范围。如果解析出的模块版本不满足该范围，Nuxt 会抛出错误。版本检查仅在依赖可以解析到 `package.json` 时才生效，因此对于项目本地模块不会起作用。
- `overrides`：在 `nuxt.options` 之上应用的配置，优先于用户配置。
- `defaults`：在 `nuxt.options` 之下应用的配置。用户配置优先于这些配置。
- `optional`：如果为 `true`，当模块缺失时不会自动安装。如果该模块已在其他地方安装，`overrides` 和 `defaults` 仍会被应用。


## Sitemap

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