插件 ​

每个 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)

同时建议您阅读关键概念:依赖,以了解 Elysia 如何处理插件之间的依赖关系。

练习 ​

让我们将 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'

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

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