主题:astro-paper GitHub - satnaing/astro-paper: A minimal, accessible and SEO-friendly Astro blog theme
样例: Lei Zhang
以下记录一些问题以及自己的解决方案,可供参考。
默认情况下,博客的 markdown 文件是放在 src/content/blog 文件夹下的,但如果文件较多,全部放在一个文件夹比较拥挤,期望放到子文件夹中,但又不希望文章的最终的 URL 中包含这个子文件夹。
src\----content\--------blog\------------2017\----------------01-my-blog.md----------------02-my-blog2.md
解决方案,自定义自己的 getCollection 方法。将所有使用 getCollection
获取博客文章的代码调用,都换成自定义的 getMyBlogCollection
,在这里,可以根据需要,做很多自定义的事情和校验。
我做了两件事情,1 去除 slug 中的自定义路径,2 检查 slug 是否以数字开头,如果是则报错。
因为文件名 01-my-blog.md 前面的数字,只是管理 markdown 文件时用来排序,并不期望其成为 URL 的一部分,所以,这里就会强制自己自定义 slug.
改造之前,一片文章的 URL 可能是这样的:https://blog.jgrass.cc/posts/2017/01-my-blog
改造之后,变成这样的:https://blog.jgrass.cc/posts/my-blog
getMyBlogCollection.ts
import { type CollectionEntry, getCollection } from "astro:content";
export default async function getMyBlogCollection< E extends CollectionEntry<"blog">,>(filter?: (entry: CollectionEntry<"blog">) => entry is E): Promise<E[]> { // const posts = await getCollection("blog", ({ data }) => !data.draft);
const posts = await getCollection("blog", filter);
const myPosts = posts.map(post => { const parts = post.slug.split("/"); // 返回最后一部分作为 slug,目的是去除 blog 下面的子文件前缀,如 2017/ const slugWithoutSubPath = parts.pop();
if (!slugWithoutSubPath) { throw Error("slug parse error. no slug?"); }
const regex = /^\d+.*/; if (slugWithoutSubPath.match(regex)) { throw Error( `slug cannot start with number, please check. ${slugWithoutSubPath}` ); }
return { ...post, slug: slugWithoutSubPath }; });
return myPosts;}
文章中引入的超链接,默认会在浏览器当前标签页打开,如何修改成在新标签页打开。
安装 rehype-external-links
在 astro.config.ts markdown 的配置中添加 rehypePlugins
astro.config.ts
import rehypeExternalLinks from "rehype-external-links";
export default defineConfig({ site: SITE.website, integrations: [ ], markdown: { rehypePlugins: [ [ rehypeExternalLinks, { target: "_blank", rel: ["noopener", "noreferrer"] }, ], ], }});
处理使用 google 字体服务生成字体失败的问题,详细描述和临时解决方案见此 issue
Failed to download dynamic font. Status: 400 · Issue #349 · satnaing/astro-paper
使用 sharp 处理图片时,经常出问题,说 sharp 未能加载,手动安装也也是这样
可以使用 squoosh 代替 sharp 进行图片优化处理
astro.config.ts
import { defineConfig, squooshImageService } from "astro/config";
// https://astro.build/configexport default defineConfig({ site: SITE.website, integrations: [ ], markdown: { }, image: { service: squooshImageService(), }});
使用 giscus 为你的 Astro 博客添加评论功能 - 掘金
The easiest way to add comments on your blog is giscus! — TheZal.dev
原文链接: https://cloud.tencent.com/developer/article/2481587
本作品采用 「署名 4.0 国际」 许可协议进行许可,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。