Astro 1.5.0 发布

作者
Matthew Phillips

Astro 1.5.0 已发布,其主要特性包括:

您可以通过运行 npm install astro@latest 来更新您的项目。

`astro preview` 的适配器支持

我们正在通过一个新的集成选项在适配器中推出对 astro preview 命令的支持,从 Node.js 适配器 @astrojs/node 开始。如果您正在使用 @astrojs/node,您现在可以通过运行以下命令来预览您的 SSR 应用:

npm run preview

适配器 API

我们将逐步更新其他 Astro 第一方适配器以支持预览功能。适配器可以通过在 astro:config:done 钩子中通过 setAdapter 函数提供 previewEntrypoint 来选择加入此功能。Node.js 适配器的代码示例如下:

export default function() {
return {
name: '@astrojs/node',
hooks: {
'astro:config:done': ({ setAdapter, config }) => {
setAdapter({
name: '@astrojs/node',
serverEntrypoint: '@astrojs/node/server.js',
previewEntrypoint: '@astrojs/node/preview.js',
exports: ['handler'],
});
// more here
}
}
};
}

Node.js 适配器中的独立模式

@astrojs/node 中新增了 独立模式 支持。通过独立模式,您无需自己编写任何服务器 JavaScript 逻辑即可启动生产服务器。服务器只需通过运行以下脚本即可启动:

node ./dist/server/entry.mjs

要启用独立模式,请在 Astro 配置中将新的 mode 选项设置为 'standalone'

import { defineConfig } from "astro/config"
import nodejs from "@astrojs/node"
export default defineConfig({
output: "server",
adapter: nodejs({
mode: "standalone",
}),
})

有关独立模式中所有可用选项的更多信息,请参阅 @astrojs/node 文档。

正在使用 Express 等自己的 HTTP 服务器框架的现有 @astrojs/node 用户可以通过将 mode 选项设置为 'middleware' 来升级,以构建到中间件模式,这与之前的行为和 API 相同。

import { defineConfig } from "astro/config"
import nodejs from "@astrojs/node"
export default defineConfig({
output: "server",
adapter: nodejs({
mode: "middleware",
}),
})

Tailwind 和 TypeScript 配置的热模块替换 (HMR)

即使在项目的初始阶段,热模块替换 (HMR) 也至关重要。在最近的一次 Astro 发布中,我们确保了对 astro.config.mjs 文件的更改会导致服务器自动重启。今天,我们正在将 HMR 支持扩展到其他配置文件。

现在,编辑您的 tsconfig.json 设置(例如,添加别名)会导致 HMR 更新。

同样地,Tailwind 配置文件更改现在也会更新。只需编辑您的 tailwind.config.(js|cjs|mjs) 文件,更改就会生效,无需重启开发服务器。

我们将在未来的版本中继续专注于 HMR 和开发体验。

API 端点改进

在 API 路由中,您现在可以在 APIContext 上获取 sitegeneratorurlclientAddresspropsredirect 字段,APIContext 是传递给 API 路由的第一个参数。这样做是为了使 APIContext 与 `.astro` 页面中的 Astro 全局对象更紧密地对齐。

例如,您可以这样使用 clientAddress(即用户的 IP 地址)来选择性地允许用户访问。

export function post({ clientAddress, redirect }) {
if (!allowList.has(clientAddress)) {
return redirect("/not-allowed")
}
}

有关新可用字段的更多信息,请查看文档

Astro.redirect 状态码

1.5 版本新增了向 Astro.redirect 传递状态码的功能。默认情况下,它使用 302,但现在您可以将另一个状态码作为第二个参数传递:

/src/pages/old-post.astro

---
// This page was moved, redirect the user to the new permanent page.
return Astro.redirect("/posts/new-post-name", 301)
---

此版本还包含了许多错误修复。感谢所有为此次出色发布做出贡献的人。有关更改的完整详情,请参阅发布说明