Skip to content
This repository has been archived by the owner on Sep 20, 2022. It is now read-only.

Added utility to generate "_redirects" file #677

Merged
merged 1 commit into from
Sep 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/many-rats-mate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'guild-docs': minor
---

Added utility to generate "\_redirects" file
43 changes: 43 additions & 0 deletions packages/docs/src/underscore-redirects.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { writeFile } from 'fs/promises';
import { join } from 'path';

class RunPromiseWebpackPlugin {
asyncHook;

constructor(asyncHook: () => Promise<void>) {
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}`);
}
})
);
}