From 2b4b80061818f1c471aafb23c0572172ef842138 Mon Sep 17 00:00:00 2001 From: Divyansh Singh <40380293+brc-dd@users.noreply.github.com> Date: Wed, 20 Jul 2022 14:31:07 +0530 Subject: [PATCH] feat: provide `transformHtml` hook (#1022) --- src/node/build/render.ts | 11 ++++++++++- src/node/config.ts | 24 ++++++++++++++++++++++-- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/node/build/render.ts b/src/node/build/render.ts index a03729e5f421..c38af2a3a216 100644 --- a/src/node/build/render.ts +++ b/src/node/build/render.ts @@ -173,7 +173,16 @@ export async function renderPage( `.trim() const htmlFileName = path.join(config.outDir, page.replace(/\.md$/, '.html')) await fs.ensureDir(path.dirname(htmlFileName)) - await fs.writeFile(htmlFileName, html) + const transformedHtml = await config.transformHtml?.(html, htmlFileName, { + siteConfig: config, + siteData, + pageData, + title, + description, + head, + content + }) + await fs.writeFile(htmlFileName, transformedHtml || html) } function resolvePageImports( diff --git a/src/node/config.ts b/src/node/config.ts index 1fac1d1b083a..28ecdec87af8 100644 --- a/src/node/config.ts +++ b/src/node/config.ts @@ -16,7 +16,8 @@ import { LocaleConfig, DefaultTheme, APPEARANCE_KEY, - createLangDictionary + createLangDictionary, + PageData } from './shared' import { resolveAliases, DEFAULT_THEME_PATH } from './alias' import { MarkdownOptions } from './markdown/markdown' @@ -77,6 +78,23 @@ export interface UserConfig { * @param siteConfig The resolved configuration. */ buildEnd?: (siteConfig: SiteConfig) => Promise + + /** + * HTML transform hook: runs before writing HTML to dist. + */ + transformHtml?: ( + code: string, + id: string, + ctx: { + siteConfig: SiteConfig + siteData: SiteData + pageData: PageData + title: string + description: string + head: HeadConfig[] + content: string + } + ) => Promise } export type RawConfigExports = @@ -95,6 +113,7 @@ export interface SiteConfig | 'lastUpdated' | 'ignoreDeadLinks' | 'buildEnd' + | 'transformHtml' > { root: string srcDir: string @@ -174,7 +193,8 @@ export async function resolveConfig( shouldPreload: userConfig.shouldPreload, mpa: !!userConfig.mpa, ignoreDeadLinks: userConfig.ignoreDeadLinks, - buildEnd: userConfig.buildEnd + buildEnd: userConfig.buildEnd, + transformHtml: userConfig.transformHtml } return config