如何使用 Astro 获取网站上的每个 URL(包括动态页面)

问题描述 投票:0回答:1

我正在为我的网站开发 404 页面,我想添加一个您的意思是链接吗?我已经弄清楚如何找到相似的页面 URL 以及如何将所有 URL 的列表从服务器传输到客户端,所以现在我只需要知道如何获取这个 URL 列表。不仅如此,我已经尝试过使用

import.meta.glob
但这并不能解析动态页面,如果可以的话我想这样做。

javascript typescript web astrojs custom-error-pages
1个回答
0
投票

因为似乎没有任何官方解决方案,所以我编写了一个小脚本,可以通过使用

import.meta.glob
导入所有 Astro 文件并使用 RegEx、
getStaticPages
replaceAll 手动解析所有动态页面来实现此目的

const modules = await Promise.all(Object.values(import.meta.glob(['./**/*.astro'])).map(fn => fn()));
let paths: string[] = [];
await modules.forEach(async (module: any) => {
  if (module.getStaticPaths == null) {
    paths.push(module.url == '' ? '/' : module.url);
    return;
  }
  const staticPaths = (await Promise.resolve(module.getStaticPaths())).map((staticPath: any) => staticPath.params);
  staticPaths.forEach((staticPath: any) => {
    const path = module.url.replaceAll(/\[([^\]]+)\]/g, (match: string) => {
      return staticPath[match.substring(1).substring(0, match.length - 2)];
    });
    paths.push(path);
  });
});

这个代码块存在多个问题,其中主要的一个是,当没有好的类型可用时,有多个实例使用any而不是自己定义一个,但它暂时作为一种解决方法,直到有更好的解决方案。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.