You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Fastify中引入静态文件?附Express实现及Fastify-View配置

在Fastify中引入静态文件的解决方案

Fastify 中处理静态文件需要使用专门的 @fastify/static 插件,这和 Express 的 express.static 功能对应。@fastify/view 仅用于模板引擎渲染,和静态文件服务是独立的功能,需要单独注册静态文件插件。

具体步骤:

  1. 安装插件
    执行以下命令安装 @fastify/static:

    npm install @fastify/static
    # 或使用 yarn
    yarn add @fastify/static
    # 或使用 pnpm
    pnpm add @fastify/static
    
  2. 注册插件并配置
    在你的 Fastify 实例中注册插件,指定静态文件目录和访问前缀:

    const fastify = require('fastify')()
    const path = require('path')
    
    // 保留你原有的 @fastify-view 配置
    fastify.register(require("@fastify/view"), {
        engine: {
            ejs: require("ejs"),
        },
        root: path.join(__dirname, "pages"),
    })
    
    // 注册静态文件服务插件
    fastify.register(require('@fastify/static'), {
      root: path.join(__dirname, 'static'), // 静态文件所在的目录
      prefix: '/static/', // 访问静态文件的路径前缀(可选)
      // 更多可选配置:比如设置 cacheControl 控制缓存,etag 启用文件校验等
    })
    
    fastify.listen({ port: 3000 }, (err) => {
      if (err) throw err
      console.log('服务已启动在 3000 端口')
    })
    

配置说明:

  • root: 必填,指定静态文件的根目录,对应你示例中 Express 里的 path.join(__dirname, "static")。
  • prefix: 可选,设置访问静态文件的路径前缀。比如配置为 /static/ 后,访问 static 目录下的 style.css 时,URL 为 http://localhost:3000/static/style.css。如果不设置该参数,直接通过根路径访问文件(如 http://localhost:3000/style.css)。

FastifyViewOptions 类型声明(中文注释)

declare namespace fastifyView {
  export interface FastifyViewOptions {
    engine: {
      ejs?: any;
      eta?: any;
      nunjucks?: any;
      pug?: any;
      handlebars?: any;
      mustache?: any;
      'art-template'?: any;
      twig?: any;
      liquid?: any;
      dot?: any;
    };
    templates?: string | string[]; // 模板文件路径,支持单个路径或路径数组
    includeViewExtension?: boolean; // 是否自动为模板文件名添加扩展名
    options?: object; // 传递给模板引擎的额外配置项
    charset?: string; // 模板文件的字符编码格式
    maxCache?: number; // 模板缓存的最大数量,设为 0 可禁用缓存
    production?: boolean; // 是否启用生产模式(通常会自动开启缓存优化)
    defaultContext?: object; // 渲染模板时的默认上下文数据
    layout?: string; // 全局通用的布局模板路径
    root?: string; // 模板文件的根目录
    viewExt?: string; // 默认的模板文件扩展名
    propertyName?: string; // 挂载到 Fastify 实例的属性名,默认为 'view'
  }
}

内容的提问来源于stack exchange,提问作者user21294053

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 00:53:10