Skip to content

静态插件

¥Static Plugin

此插件可以为 Elysia 服务器提供静态文件/文件夹。

¥This plugin can serve static files/folders for Elysia Server

使用以下工具安装:

¥Install with:

bash
bun add @elysiajs/static

然后使用它:

¥Then use it:

typescript
import { 
Elysia
} from 'elysia'
import {
staticPlugin
} from '@elysiajs/static'
new
Elysia
()
.
use
(
staticPlugin
())
.
listen
(3000)

默认情况下,静态插件默认文件夹为 public,并使用 /public 前缀注册。

¥By default, the static plugin default folder is public, and registered with /public prefix.

假设你的项目结构如下:

¥Suppose your project structure is:

| - src
  | - index.ts
| - public
  | - takodachi.png
  | - nested
    | - takodachi.png

可用路径将变为:

¥The available path will become:

  • /public/takodachi.png

  • /public/nested/takodachi.png

配置

¥Config

以下是插件接受的配​​置。

¥Below is a config which is accepted by the plugin

assets

@default "public"

要作为静态公开的文件夹的路径

¥Path to the folder to expose as static

prefix

@default "/public"

注册公共文件的路径前缀

¥Path prefix to register public files

ignorePatterns

@default []

应忽略不作为静态文件的文件列表

¥List of files to ignore from serving as static files

staticLimit

@default 1024

默认情况下,静态插件会使用静态名称将路径注册到路由,如果超出限制,路径将被延迟添加到路由以减少内存使用。在内存和性能之间进行权衡。

¥By default, the static plugin will register paths to the Router with a static name, if the limits are exceeded, paths will be lazily added to the Router to reduce memory usage. Tradeoff memory with performance.

alwaysStatic

@default false

如果设置为 true,则静态文件路径将跳过 staticLimits 并注册到路由。

¥If set to true, static files path will be registered to Router skipping the staticLimits.

headers

@default {}

设置文件的响应标头

¥Set response headers of files

indexHTML

@default false

如果设置为 true,则对于任何既不匹配路由也不匹配任何现有静态文件的请求,都将提供静态目录中的 index.html 文件。

¥If set to true, the index.html file from the static directory will be served for any request that is matching neither a route nor any existing static file.

模式

¥Pattern

以下是使用该插件的常见模式。

¥Below you can find the common patterns to use the plugin.

单个文件

¥Single file

假设你只想返回一个文件,你可以使用 file 而不是静态插件。

¥Suppose you want to return just a single file, you can use file instead of using the static plugin

typescript
import { Elysia, file } from 'elysia'

new Elysia()
    .get('/file', file('public/takodachi.png'))