From 754c2a190baac2a1ccce47fa37e863865e0072fd Mon Sep 17 00:00:00 2001 From: Jason Cox Date: Wed, 23 Sep 2020 08:30:06 -0700 Subject: [PATCH] Generate v1 -> v2 redirects for all production pages (#611) --- v2/gatsby-node.js | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/v2/gatsby-node.js b/v2/gatsby-node.js index 0ae88690d..2ac995f17 100644 --- a/v2/gatsby-node.js +++ b/v2/gatsby-node.js @@ -39,11 +39,11 @@ const createRedirectForEachLocale = async (createRedirect, page) => { await forEachLocale( page, async (page, context, localizationParams, localizedPath) => { + // By default, assume v1 paths of the form `/path.html` transform to + // v2 paths of the form `/path/`. createRedirect({ - fromPath: localizedPath, - // By default, assume paths of the form `/path/` transform to - // v1 paths of the form `/path.html` - toPath: localizedPath.replace(/\/$/, "") + ".html", + fromPath: localizedPath.replace(/\/$/, "") + ".html", + toPath: localizedPath, redirectInBrowser: true, isPermanent: false, }) @@ -92,7 +92,13 @@ exports.createPages = async ({ graphql, actions, reporter }) => { // In production, we redirect in-development v2 pages to v1 equivalent routes. // In non-prod environments, we create all pages and do not redirect. if (process.env.GATSBY_APP_ENV == "prod") { - await createRedirectForEachLocale(createRedirect, page) + await createRedirectForEachLocale((redirectArgs) => { + createRedirect({ + ...redirectArgs, + fromPath: redirectArgs.toPath, + toPath: redirectArgs.fromPath, + }) + }, page) } else { await createPageForEachLocale(createPage, page) } @@ -102,20 +108,15 @@ exports.createPages = async ({ graphql, actions, reporter }) => { exports.onCreatePage = async ({ page, - actions: { createPage, deletePage }, + actions: { createPage, createRedirect, deletePage }, }) => { // Delete the original page (since we are gonna create localized versions of it) await deletePage(page) // Create one page for each locale - await forEachLocale( - page, - (page, context, localizationParams, localizedPath) => { - createPage({ - ...page, - path: localizedPath, - context, - }) - } - ) + await createPageForEachLocale(createPage, page) + + // Although not all pages have v1 equivalents, it doesn't hurt to generate + // redirects for all of them to point at v2 pages. + await createRedirectForEachLocale(createRedirect, page) }