From 4496ff880cc7138498456b1d1bf9c1c297b3da94 Mon Sep 17 00:00:00 2001 From: kacan98 Date: Mon, 25 Mar 2024 10:34:46 +0100 Subject: [PATCH] When refreshing on anything but the root page (when in GH pages) redirects to GH 404 - fix that --- .github/workflows/deployment.yml | 2 +- package.json | 4 ++-- scripts/afterBuild.js | 24 ++++++++++++++++++++++++ 3 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 scripts/afterBuild.js diff --git a/.github/workflows/deployment.yml b/.github/workflows/deployment.yml index a2c2aa7..3aac219 100644 --- a/.github/workflows/deployment.yml +++ b/.github/workflows/deployment.yml @@ -2,7 +2,7 @@ name: Build and Deploy on: push: branches: - - master + [fix-bug-refresh-redirects-to-github-404] permissions: contents: write concurrency: diff --git a/package.json b/package.json index 01ff719..f04d962 100644 --- a/package.json +++ b/package.json @@ -4,8 +4,8 @@ "scripts": { "ng": "ng", "start": "ng serve", - "build": "ng build", - "build:gh-pages": "ng build --base-href /team-app/", + "build": "ng build && node scripts/afterBuild.js", + "build:gh-pages": "npm run build --base-href /team-app/", "watch": "ng build --watch --configuration development", "test": "ng test" }, diff --git a/scripts/afterBuild.js b/scripts/afterBuild.js new file mode 100644 index 0000000..4d04aca --- /dev/null +++ b/scripts/afterBuild.js @@ -0,0 +1,24 @@ +const fs = require('fs'); +const path = require('path'); + +// because GH pages doesn't support SPA routing, we need to redirect all 404s to the root +const distPath = path.join(__dirname, '../dist/team-app'); +const indexPath = path.join(distPath, 'index.html'); +const notFoundPath = path.join(distPath, '404.html'); + +fs.copyFileSync(indexPath, notFoundPath); + +const redirectScript = ` + +`; + +let htmlContent = fs.readFileSync(notFoundPath, 'utf8'); + +// Replace the closing body tag with the script followed by the closing body tag +htmlContent = htmlContent.replace('', redirectScript); + +fs.writeFileSync(notFoundPath, htmlContent);