Skip to content
Our Sponsors
Open in Anthropic

title: 插件 - Elysia 教程 layout: false search: false authors: [] head: - - meta - property: 'og:title' content: 插件 - Elysia 教程

- - meta
  - name: 'description'
    content: 学习如何在 Elysia 中使用插件,通过可复用的组件和功能来增强您的 Web 应用程序。

- - meta
  - property: 'og:description'
    content: 学习如何在 Elysia 中使用插件,通过可复用的组件和功能来增强您的 Web 应用程序。

插件

每个 Elysia 实例都可以通过 use 方法与其他实例进行即插即用。

typescript
import { Elysia } from 'elysia'

const user = new Elysia()
	.get('/profile', '用户资料')
	.get('/settings', '用户设置')

new Elysia()
	.use(user) 
	.get('/', '主页')
	.listen(3000)

一旦应用,来自 user 实例的所有路由将在 app 实例中可用。

插件配置

您还可以创建一个接受参数并返回一个 Elysia 实例的插件,以制作一个更动态的插件。

typescript
import { Elysia } from 'elysia'

const user = ({ log = false }) => new Elysia() 
	.onBeforeHandle(({ request }) => {
		if (log) console.log(request)
	})
	.get('/profile', '用户资料')
	.get('/settings', '用户设置')

new Elysia()
	.use(user({ log: true })) 
	.get('/', '主页')
	.listen(3000)

练习

让我们将 user 实例应用到 app 实例。

  1. Apply Plugin

    Let's apply the user plugin to the main app.

Show answer

与上面的示例类似,我们可以使用 use 方法将 user 实例插入到 app 实例中。

typescript
import { Elysia } from 'elysia'

new Elysia()
	.get('/profile', '用户资料')
	.get('/settings', '用户设置')

const app = new Elysia()
	.use(user) 
	.get('/', '主页')
	.listen(3000)
  • index.ts