generated from technologiestiftung/template-repo-citylab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate.js
49 lines (37 loc) · 1.38 KB
/
generate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const toAbsolute = (p) => path.resolve(__dirname, p)
/**
* The following files are missing at the beginning
* because they are generated during the build step.
*/
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('<title></title>', `<title>${pageTitle}</title>`)
.replace(`<!--app-html-->`, appHtml)
const filePath = `dist${path}index.html`
writeFileSyncRecursive(toAbsolute(filePath), html)
console.log('pre-rendered:', filePath)
}
}
function writeFileSyncRecursive(filename, content) {
const dirname = path.dirname(filename);
// Check if the directory exists
if (!fs.existsSync(dirname)) {
// If not, create the directory recursively
fs.mkdirSync(dirname, { recursive: true });
}
// Write the file
fs.writeFileSync(filename, content);
}
generateStaticPages();