quartz-research-note/quartz/plugins/emitters/aliases.ts

54 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-07-13 07:19:35 +00:00
import { CanonicalSlug, FilePath, ServerSlug, relativeToRoot } from "../../path"
2023-06-17 02:41:59 +00:00
import { QuartzEmitterPlugin } from "../types"
import path from 'path'
export const AliasRedirects: QuartzEmitterPlugin = () => ({
name: "AliasRedirects",
getQuartzComponents() {
return []
},
2023-07-13 07:19:35 +00:00
async emit(contentFolder, _cfg, content, _resources, emit): Promise<FilePath[]> {
const fps: FilePath[] = []
2023-06-17 02:41:59 +00:00
for (const [_tree, file] of content) {
const ogSlug = file.data.slug!
const dir = path.relative(contentFolder, file.dirname ?? contentFolder)
2023-07-13 07:19:35 +00:00
let aliases: CanonicalSlug[] = []
2023-06-17 02:41:59 +00:00
if (file.data.frontmatter?.aliases) {
aliases = file.data.frontmatter?.aliases
} else if (file.data.frontmatter?.alias) {
aliases = [file.data.frontmatter?.alias]
}
for (const alias of aliases) {
2023-07-13 07:19:35 +00:00
const slug = (alias.startsWith("/")
2023-06-17 02:41:59 +00:00
? alias
2023-07-13 07:19:35 +00:00
: path.posix.join(dir, alias)) as ServerSlug
2023-06-17 02:41:59 +00:00
2023-07-13 07:19:35 +00:00
const fp = slug + ".html" as FilePath
2023-06-17 02:41:59 +00:00
const redirUrl = relativeToRoot(slug, ogSlug)
await emit({
content: `
<!DOCTYPE html>
<html lang="en-us">
<head>
<title>${ogSlug}</title>
<link rel="canonical" href="${redirUrl}">
<meta name="robots" content="noindex">
<meta charset="utf-8">
<meta http-equiv="refresh" content="0; url=${redirUrl}">
</head>
</html>
`,
slug,
ext: ".html",
})
fps.push(fp)
}
}
return fps
}
})