Debugging an Astro template
Some notes on debugging Astro’s free template Astrology-i18n
In many astror templates, they all use the image source with the URL of images.unsplash.com. The domestic response time to this address is too slow, so there are some improvements below, based on AI coding.
A My question: I need to be able to display local images and external URL images at the same time.
google AI answer: In Astro 5.0, to make a field (such as heroImage) compatible with both local relative paths and external URL links, you need to use Zod’s z.union or z.or to define the union type and combine it with the image() validator.
The following are the specific code implementation and usage steps:
- Modify src/content.config.ts
You need to deconstruct the image helper function and define the field to accept either a “locally optimized image” or a “plain string (URL)”.
import { defineCollection, z } from 'astro:content';import { glob } from 'astro/loaders';
// ... 保持 LANGS 定义不变
const post = defineCollection({ loader: glob({ pattern: '**/*.{md,mdx,markdown}', base: './src/content/posts' }), // 注意这里:schema 变成了一个接收 { image } 参数的函数 schema: ({ image }) => z.object({ title: z.string(), description: z.string(), category: z.string(), tags: z.array(z.string()).default([]), pubDate: z.coerce.date(), updatedDate: z.coerce.date().optional(), author: z.string().default('Astro'),
// ✅ 核心修改:同时支持本地图片对象或 URL 字符串 heroImage: image().or(z.string()),
heroImageAlt: z.string(), locales: z.enum(LANGS), draft: z.boolean().default(false), featured: z.boolean().default(false), }),});
// page 和 author 集合如果需要也可以按此方式修改- How to fill in Markdown/MDX? You can fill it in flexibly according to the image source: use local images (the format will be automatically compressed and converted):
---title: "使用本地图片的文章"heroImage: "./my-cover.jpg" # 必须以 ./ 开头,指向当前目录或相对路径heroImageAlt: "本地图片描述"---使用外部 URL(直接引用,不进行本地压缩):
---title: "使用链接的文章"heroImage: "images.unsplash.com" # 完整的 URLheroImageAlt: "外部图片描述"---- Render in .astro component Since heroImage may now be an “image object” or a “string”, when passed directly to the <Image /> component, if it is an external string, Astro requires that width and height must be provided manually (unless you have made special settings for this domain name in the configuration). Recommended robust rendering methods:
---// src/components/PostCard.astro 或 src/pages/posts/[id].astroimport { Image } from 'astro:assets';const { post } = Astro.props;const { heroImage, heroImageAlt } = post.data;
// 判断是否是远程链接(简单的字符串检查)const isExternal = typeof heroImage === 'string';---
{ isExternal ? ( // 如果是外部链接,直接使用标准 img 标签或指定远程策略的 Image <img src={heroImage} alt={heroImageAlt} class="w-full h-auto rounded-lg" /> ) : ( // 如果是本地图片,利用 Astro Image 组件进行自动优化(转 WebP/AVIF 等) <Image src={heroImage} alt={heroImageAlt} width={800} height={450} class="rounded-lg" /> )}4.Why is it best to do this?
Build performance: While the 2025 Astro build is fast, it still takes time to process thousands of local images. By setting heroImage to union, you can use local optimization for high-quality cover images and external links for ordinary reference images, balancing visual quality and build speed. Security: For external URLs, you have configured remotePatterns (such as Unsplash) in astro.config.mjs, which ensures that only external images from trusted domain names will be displayed [1].
Compatibility: When you migrate a website from Vercel to your own server, this approach does not require the server to install any underlying image libraries like Sharp, because local images are processed during the build phase on your development computer, while external images are downloaded directly by the user’s browser.
D I ask: md syntax
google ai Answer: When using Markdown (MD/MDX) in Astro 5.0+, in addition to the standard syntax, you also need to pay special attention to the path processing of the Content Layer and the integration of Astro-specific components. Here is a complete guide to Markdown syntax for your current project configuration:
- Basic MD syntax (standard) These are completely universal in Astro:
# 一级标题## 二级标题
**加粗**,*斜体*,~~删除线~~
- 无序列表1. 有序列表
[链接文字](https://google.com)
> 引用块- Frontmatter 配置 (关键) 根据你之前定义的 defineCollection schema,你的 MDX 开头必须包含这些字段,否则会构建报错:
---title: "我的 2025 占星指南"description: "这是一篇关于星座的深度分析"category: "占星"tags: ["星座", "运势"]pubDate: 2025-12-31heroImage: "../../assets/images/posts/kk.jpg" # 本地图片路径heroImageAlt: "封面图描述"locales: "zh" # 必须是你定义的 LANGS 之一draft: false # 是否为草稿featured: true # 是否推荐---- Code block rendering (Expressive Code) Because you configured astro-expressive-code, your code block supports advanced features:
```js {1, 3-4} title="example.js" ins={6} del={2}const a = 1; // 这一行会被高亮const b = 2; // 这一行会被标记为删除const c = 3;const d = 4;// 下面这一行会被标记为新增console.log("Hello Astro 2025");The actual displayed effect is as follows:```js {1, 3-4} title="example.js" ins={6} del={2}const a = 1; // 这一行会被高亮const b = 2; // 这一行会被标记为删除const c = 3;const d = 4;// 下面这一行会被标记为新增console.log("Hello Astro 2025");The meaning is as follows:
{1}: Highlight the first line. title=”…”: Add a title bar to the code block. ins /del: simulate the new/delete effect of Git.
4.MDX 特有:直接使用 Astro 组件 由于你安装了 @astrojs/mdx,你可以在 Markdown 里直接写交互组件或 HTML。 示例:在文章中插入你那个 GitHub 日历组件
import GitHubActivityCalendar from '../../components/widgets/GitHubActivityCalendar.astro';
# 个人动态
下面是我的 GitHub 贡献统计:
<GitHubActivityCalendar username="yourid" client:visible />Note: Relative paths must be used when introducing components into MDX.
- Image processing skills In Astro in 2025, there are two MD writing methods for processing local images:
标准 MD 写法(适合正文): -> Astro 会自动压缩并转为 WebP。HTML/组件写法(适合需要精细控制):html<img src="../../assets/images/photo.jpg" width="400" alt="说明" />- Special function: Automatically display the last modification time
You added the remarkModifiedTime plug-in to the configuration. If you want to display “Last updated on: 2025-xx-xx” on the page, you usually need to obtain it through remarkPluginFrontmatter in the .astro template instead of writing it directly in MD syntax.
- Pitfall Avoidance Guide (2025 Common Mistakes)
a. Path alias: In MD/MDX, the @/assets/alias cannot be used, and ../../must be used.
b. Blank line: In MDX, a blank line must be left between the Import statement and the Markdown body.
c. i18n path: Make sure your MD file storage location corresponds to the locales field. Although you used routing: ‘manual’, if the locales in src/content/posts/en/test.md is written as zh, it may cause confusion in the Pagefind search index.
- The astro system components are only displayed in text mode in the MD file.
If there is a component similar to <Image /> in the MD file, please add the escape character \ to display it as text instead of a component.
Published at: Dec 31, 2025