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

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 的重大重写和内部迁移,以提高性能、功能和稳定性。

详情查看发布公告

© 版权声明
THE END
喜欢就支持一下吧
点赞0

Warning: mysqli_query(): (HY000/3): Error writing file '/tmp/MYe3QsEp' (Errcode: 28 - No space left on device) in /www/wwwroot/583.cn/wp-includes/class-wpdb.php on line 2345
admin的头像-五八三
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

图形验证码
取消
昵称代码图片