---
title: "插件和中间件"
description: "了解如何将 Nuxt 2 的插件和中间件迁移到 Nuxt 3。"
canonical_url: "https://nuxt.zhcndoc.com/docs/4.x/migration/plugins-and-middleware"
---
# 插件和中间件

> 了解如何将 Nuxt 2 的插件和中间件迁移到 Nuxt 3。

## 插件

插件现在有不同的格式，并且只接受一个参数（`nuxtApp`）。

::code-group
```ts [Nuxt 2]
export default (ctx, inject) => {
  inject('injected', () => 'my injected function')
}
```

```ts [Nuxt 3]
export default defineNuxtPlugin((nuxtApp) => {
  // now available on `nuxtApp.$injected`
  nuxtApp.provide('injected', () => 'my injected function')

  // You can alternatively use this format, which comes with automatic type support
  return {
    provide: {
      injected: () => 'my injected function',
    },
  }
})
```
::

::read-more{to="https://nuxt.zhcndoc.com/docs/4.x/directory-structure/app/plugins"}
::

::read-more{to="https://nuxt.zhcndoc.com/docs/4.x/api/composables/use-nuxt-app"}
了解有关 `nuxtApp` 格式的更多信息。
::

### 迁移

1. 将你的插件迁移为使用 `defineNuxtPlugin` 辅助函数。
2. 删除 `nuxt.config` 中插件数组里位于 `app/plugins/` 文件夹的任何条目。该目录下顶层的所有文件（以及任何子目录中的 index 文件）将自动注册。你可以通过文件名来指明是在客户端还是服务器端加载，而不必再设置 `mode` 为 `client` 或 `server`。例如，`~/plugins/my-plugin.client.ts` 将只在客户端加载。

## 路由中间件

路由中间件的格式也不同。

::code-group
```js [Nuxt 2]
export default function ({ store, redirect }) {
  // If the user is not authenticated
  if (!store.state.authenticated) {
    return redirect('/login')
  }
}
```

```ts [Nuxt 3]
export default defineNuxtRouteMiddleware((to, from) => {
  const auth = useState('auth')
  if (!auth.value.authenticated) {
    return navigateTo('/login')
  }
})
```
::

与 Nuxt 2 类似，放在 `~/middleware` 文件夹中的路由中间件会被自动注册。然后你可以在组件中按名称指定它。不过，这里使用的是 `definePageMeta`，而不是作为组件选项来指定。

`navigateTo` 是众多路由辅助函数之一。

::read-more{to="https://nuxt.zhcndoc.com/docs/4.x/directory-structure/app/middleware"}
::

### 迁移

1. 将你的路由中间件迁移为使用 `defineNuxtRouteMiddleware` 辅助函数。
2. 任何全局中间件（例如在你的 `nuxt.config` 中的）都可以放在 `~/middleware` 文件夹中，并使用 `.global` 扩展名，例如 `~/middleware/auth.global.ts`。


## Sitemap

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