@theguild/components
Version:
41 lines (40 loc) • 1.33 kB
JavaScript
import { writeFile } from "fs/promises";
import { join } from "path";
class RunPromiseWebpackPlugin {
constructor(asyncHook) {
this.asyncHook = asyncHook;
}
apply(compiler) {
compiler.hooks.beforeCompile.tapPromise("RunPromiseWebpackPlugin", this.asyncHook);
}
}
let isWarningPrinted = false;
function applyUnderscoreRedirects(config, meta) {
config.plugins.push(
new RunPromiseWebpackPlugin(async () => {
const outDir = meta.dir;
const outFile = join(outDir, "./public/_redirects");
try {
const redirects = meta.config.redirects ? Array.isArray(meta.config.redirects) ? meta.config.redirects : await meta.config.redirects() : [];
if (redirects.length === 0) {
if (!isWarningPrinted) {
console.warn(
'[@theguild/components] No redirects defined, no "_redirect" file is created!'
);
isWarningPrinted = true;
}
return;
}
const redirectsTxt = redirects.map((r) => `${r.source} ${r.destination} ${r.permanent ? 301 : 302}`).join("\n");
await writeFile(outFile, redirectsTxt);
} catch (error) {
throw new Error(
`Failed to generate "_redirects" file during build: ${error.message}`
);
}
})
);
}
export {
applyUnderscoreRedirects
};