diff --git a/.changeset/many-rats-mate.md b/.changeset/many-rats-mate.md new file mode 100644 index 00000000..35cedf56 --- /dev/null +++ b/.changeset/many-rats-mate.md @@ -0,0 +1,5 @@ +--- +'guild-docs': minor +--- + +Added utility to generate "\_redirects" file diff --git a/packages/docs/src/underscore-redirects.ts b/packages/docs/src/underscore-redirects.ts new file mode 100644 index 00000000..51d2c9c1 --- /dev/null +++ b/packages/docs/src/underscore-redirects.ts @@ -0,0 +1,43 @@ +import { writeFile } from 'fs/promises'; +import { join } from 'path'; + +class RunPromiseWebpackPlugin { + asyncHook; + + constructor(asyncHook: () => Promise) { + this.asyncHook = asyncHook; + } + + apply(compiler: any) { + compiler.hooks.beforeCompile.tapPromise('RunPromiseWebpackPlugin', this.asyncHook); + } +} + +export function applyUnderscoreRedirects(config: any, meta: any) { + config.plugins.push( + new RunPromiseWebpackPlugin(async () => { + const outDir = meta.dir; + const outFile = join(outDir, './public/_redirects'); + + try { + const redirects: any[] = meta.config.redirects + ? Array.isArray(typeof meta.config.redirects) + ? typeof meta.config.redirects + : await meta.config.redirects() + : []; + + if (redirects.length > 0) { + const redirectsTxt = redirects + .map(r => `${r.source} ${r.destination} ${r.permanent ? '301' : '302'}`) + .join('\n'); + await writeFile(outFile, redirectsTxt); + } else { + console.warn(`No redirects defined, no "_redirect" file is created!`); + } + } catch (e) { + console.error('Error while generating redirects file: ', e); + throw new Error(`Failed to generate "_redirects" file during build: ${(e as Error).message}`); + } + }) + ); +}