---
title: "在 Nuxt 中使用 Vite 插件"
description: "了解如何将 Vite 插件集成到你的 Nuxt 项目中。"
canonical_url: "https://nuxt.zhcndoc.com/docs/4.x/guide/recipes/vite-plugin"
---
# 在 Nuxt 中使用 Vite 插件

> 了解如何将 Vite 插件集成到你的 Nuxt 项目中。

虽然 Nuxt 模块提供了广泛的功能，但有时特定的 Vite 插件可能更直接地满足你的需求。

首先，我们需要安装 Vite 插件；在本例中，我们将使用 `@rollup/plugin-yaml`：

<code-group sync="pm">

```bash [npm]
npm install @rollup/plugin-yaml
```

```bash [yarn]
yarn add @rollup/plugin-yaml
```

```bash [pnpm]
pnpm add @rollup/plugin-yaml
```

```bash [bun]
bun add @rollup/plugin-yaml
```

```bash [deno]
deno add npm:@rollup/plugin-yaml
```

</code-group>

接下来，我们需要导入它并将其添加到 [`nuxt.config.ts`](https://nuxt.zhcndoc.com/docs/4.x/directory-structure/nuxt-config) 文件中：

```ts [nuxt.config.ts]
import yaml from '@rollup/plugin-yaml'

export default defineNuxtConfig({
  vite: {
    plugins: [
      yaml(),
    ],
  },
})
```

现在我们已经安装并配置了 Vite 插件，就可以在项目中直接使用 YAML 文件了。

例如，我们可以有一个 `config.yaml` 用于存储配置数据，并在 Nuxt 组件中导入这些数据：

<code-group>

```yaml [data/hello.yaml]
greeting: "Hello, Nuxt with Vite!"
```

```vue [app/components/Hello.vue]
<script setup>
import config from '~/data/hello.yaml'
</script>

<template>
  <h1>{{ config.greeting }}</h1>
</template>
```

</code-group>

## 在 Nuxt 模块中使用 Vite 插件

如果你正在开发 Nuxt 模块并需要添加 Vite 插件，应该使用 [`addVitePlugin`](https://nuxt.zhcndoc.com/docs/4.x/api/kit/builder#addviteplugin) 工具：

```ts [modules/my-module.ts]
import { addVitePlugin, defineNuxtModule } from '@nuxt/kit'
import yaml from '@rollup/plugin-yaml'

export default defineNuxtModule({
  setup () {
    addVitePlugin(yaml())
  },
})
```

在 Nuxt 5+ 中，对于特定环境的插件，请使用 `applyToEnvironment()` 方法：

```ts [modules/my-module.ts]
import { addVitePlugin, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup () {
    addVitePlugin(() => ({
      name: 'my-client-plugin',
      applyToEnvironment (environment) {
        return environment.name === 'client'
      },
      // Plugin configuration
    }))
  },
})
```

<important>

如果您正在编写需要访问已解析的 Vite 配置的代码，您应该在 Vite 插件中使用 `config` 和 `configResolved` 钩子，而不是使用 Nuxt 的 `vite:extend`、`vite:extendConfig` 和 `vite:configResolved`。

</important>

<read-more to="https://nuxt.zhcndoc.com/docs/4.x/api/kit/builder#addviteplugin">

在 Nuxt Kit 文档中了解有关 `addVitePlugin` 的更多信息。

</read-more>


## Sitemap

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