Skip to content

Commit

Permalink
When refreshing on anything but the root page (when in GH pages) redi…
Browse files Browse the repository at this point in the history
…rects to GH 404 - fix that
  • Loading branch information
kacan98 committed Mar 25, 2024
1 parent 34a6850 commit 8dc348b
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/deployment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: Build and Deploy
on:
push:
branches:
- master
[fix-bug-refresh-redirects-to-github-404]
permissions:
contents: write
concurrency:
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"build:gh-pages": "ng build --base-href /team-app/",
"build:gh-pages": "ng build --base-href /team-app/ && node scripts/afterBuild.js",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
Expand Down
24 changes: 24 additions & 0 deletions scripts/afterBuild.js
Original file line number Diff line number Diff line change
@@ -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 = `
<script>
if (location.pathname !== "/") {
location.replace('/#' + location.pathname);
}
</script>
</body>`;

let htmlContent = fs.readFileSync(notFoundPath, 'utf8');

// Replace the closing body tag with the script followed by the closing body tag
htmlContent = htmlContent.replace('</body>', redirectScript);

fs.writeFileSync(notFoundPath, htmlContent);

0 comments on commit 8dc348b

Please sign in to comment.