您现在的位置是:首页 > 文章详情

现代化静态站点生成器 Astro 发布 2.6,引入中间件 (Middleware)

日期:2023-06-08点击:242

Astro 2.6 已正式发布。在该版本中,多项实验性功能进入稳定状态,包括:Middleware(中间件)Hybrid SSR output mode(混合 SSR 输出模式)Custom client directives(自定义客户端指令)和 CSS inlining(CSS 内联)

此外还引入了许多新功能和改进,包括用于管理重定向的实验性新功能:


  • Middleware(中间件)

Middleware 目前已到达稳定阶段。该功能支持在页面被渲染并返回给用户之前或之后运行代码。这为 Astro 项目带来了新的控制层,并解锁了用于身份验证、重定向、修改 header 等新 hook。

 // src/middleware.ts export async function onRequest(context, next) { // Do something before the request is handled. const response = await next() // Or, do something before the response is returned. return response }

下面是一个示例,说明如何在 Middleware 中实现基本身份验证检查,并将加载的用户上下文传递到页面路由:

 // src/middleware.ts // Example: A simple authentication check in middleware. export async function onRequest({ cookies, locals }, next) { // Check for the "sid" user session ID cookie. // Return a 405 (Not Allowed) if the cookie is missing. const sessionId = cookies.get("sid"); if (!sessionId) { return new Response(null, {status: 405}); } // Use your own `getUser()` function to validate the user. // Return a 405 (Not Allowed) if the user isn't real. const user = await getUser(sessionId); if (!user) { return new Response(null, {status: 405}); } // Attach the loaded user to the `locals` object. // Now, it can be read in the page route! locals.user = user; // Return `next()` to return the response. return next(); }
  • CSS 内联

Astro 2.6 引入了一个新的配置选项,可以自动将 CSS 的小片段内联到 HTML 中。这种优化可以通过减少加载页面所需的请求和外部样式表的数量来加速大多数页面(尤其是在首次加载时)。现在可以通过在配置文件中设置inlineStylesheets: "auto"来尝试:

 // astro.config.mjs import { defineConfig } from "astro/config" export default defineConfig({ build: { inlineStylesheets: "auto", }, })
  • 改进语言工具

Astro 的语言工具通过@astrojs/language-server的 2.0 版本和 Astro 的 2.0 VSCode 扩展获得了重大升级。此版本完成了对 Volar 的重大重写和内部迁移,以提高性能、功能和稳定性。

详情查看发布公告

原文链接:https://www.oschina.net/news/244404/astro-2-6-0-released
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章