Skip to content

Commit

Permalink
feat: add dynamic page titles
Browse files Browse the repository at this point in the history
Signed-off-by: Raphael Arce <[email protected]>
  • Loading branch information
raphael-arce committed Aug 22, 2024
1 parent eb35024 commit a29a98a
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 2 deletions.
6 changes: 5 additions & 1 deletion generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,18 @@ const toAbsolute = (p) => path.resolve(__dirname, p)
const template = fs.readFileSync(toAbsolute('dist/index.html'), 'utf-8');
const { render } = await import('./dist/server/entry-server.js');
const { routes } = await import('./dist/assets/routes/routes.js');
const { content } = await import('./dist/assets/content/content.js');

function generateStaticPages() {
for (const { path } of routes) {
console.log('path:', path);

const appHtml = render(path)
const pageTitle = content[path].title

const html = template.replace(`<!--app-html-->`, appHtml)
const html = template
.replace('<title></title>', `<title>${pageTitle}</title>`)
.replace(`<!--app-html-->`, appHtml)

const filePath = `dist${path}index.html`
writeFileSyncRecursive(toAbsolute(filePath), html)
Expand Down
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite React SSG</title>
<title></title>
</head>
<body>
<div id="root"><!--app-html--></div>
Expand Down
4 changes: 4 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@ import React from "react";
import { Route, Routes } from 'react-router-dom'
import { routes } from './routes/routes'
import { content } from "./content/content";
import { usePageTitle } from "./hooks/use-page-title";

const pages: Record<string, { default: React.FC }> = import.meta.glob('./pages/**/*.tsx', { eager: true })

export function App() {

usePageTitle();

return (
<>
<nav>
Expand Down
8 changes: 8 additions & 0 deletions src/hooks/use-page-title.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import {useEffect} from "react";
import {content} from "../content/content.ts";

export function usePageTitle() {
useEffect(() => {
document.title = content[window.location.pathname].title
}, [])
}

0 comments on commit a29a98a

Please sign in to comment.