Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

generate temp files #185

Merged
merged 10 commits into from
Jul 3, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/front/config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export default {
outDirSsrClient: resolve("dist/ssr/client"),
outDirSpa: resolve("dist/spa"),
outDirStaticClient: resolve("dist/static/client"),
outDirStaticClientTemp: resolve("dist/static/_temp"),
outDirStaticScripts: resolve("dist/static/scripts"),

// Input entry files array
Expand Down
2 changes: 1 addition & 1 deletion apps/front/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"build:ssr-server": "vite build --ssr src/index-server.tsx --outDir dist/ssr/server",
"build:ssr": "npm run build:ssr-scripts && npm run build:ssr-client && npm run build:ssr-server",
"build:static-scripts": "vite build -c vite.static-scripts.config.ts",
"build:static-client": "vite build --outDir dist/static/client",
"build:static-client": "vite build --outDir dist/static/_temp",
Bastou marked this conversation as resolved.
Show resolved Hide resolved
"build:static": "npm run build:static-scripts && npm run build:static-client && npm run generate",
"generate": "node dist/static/scripts/exe-prerender.js",
"build": "npm run build:spa && npm run build:ssr && npm run build:static",
Expand Down
9 changes: 4 additions & 5 deletions apps/front/prerender/exe-prerender-server.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import express from "express"
import { prerender } from "./prerender"
import chalk from "chalk"
import { fetchAvailableUrls } from "./urls"
import config from "../config/config"
import express from "express"
import * as process from "process"
import { loadEnv } from "vite"
import { prerender } from "./prerender"
import { fetchAvailableUrls } from "./urls"

const envs = loadEnv("", process.cwd(), "")
const port = envs.PRERENDER_SERVER_NODE_PORT || process.env.PRERENDER_SERVER_NODE_PORT
Expand All @@ -26,7 +25,7 @@ app.get("/generate", async (req, res) => {

// second arg "./static" is matching cher-ami deploy conf
// need to be edited if we want to start this server locally
await prerender(urlsArray, config.outDirStaticClient)
await prerender(urlsArray)
res?.send("Generated static pages: " + urlsArray.join(", "))
})

Expand Down
150 changes: 126 additions & 24 deletions apps/front/prerender/prerender.ts
Original file line number Diff line number Diff line change
@@ -1,57 +1,90 @@
// @ts-ignore
import { render } from "~/index-server"
import * as mfs from "@cher-ami/mfs"
import path from "path"
import chalk from "chalk"
import * as fs from "fs/promises"
import path from "path"
import { JSXElementConstructor, ReactElement } from "react"
import { renderToPipeableStream, renderToString } from "react-dom/server"
import { loadEnv } from "vite"
import { render } from "~/index-server"
import config from "../config/config.js"
import { isRouteIndex } from "./helpers/isRouteIndex"
import { ManifestParser } from "./helpers/ManifestParser"
import { renderToPipeableStream, renderToString } from "react-dom/server"
import { JSXElementConstructor, ReactElement } from "react"
import { Dirent } from "fs"
import { rejects } from "assert"

/**
* Prerender
* Create static HTML files from react render DOM
* @param urls: Urls to generate
* @param outDirStatic: Generation destination directory
*/
export const prerender = async (
urls: string[],
outDirStatic = config.outDirStaticClient
) => {
const indexTemplateSrc = `${outDirStatic}/index-template.html`
export const prerender = async (urls: string[]) => {
// Define output folders (_temp & client)
const outDirStatic = config.outDirStaticClient
const outDirStaticTemp = config.outDirStaticClientTemp

// copy index as template to avoid the override with the generated static index.html bellow
if (!(await mfs.fileExists(indexTemplateSrc))) {
await mfs.copyFile(`${outDirStatic}/index.html`, indexTemplateSrc)
}
// Define if comes from :
// - build (npm run build:static)
// - generate (server /generate or npm run generate)
const isGenerate = !(await mfs.fileExists(`${outDirStaticTemp}/.vite/manifest.json`))

// get script tags to inject in render
const base = loadEnv("", process.cwd(), "").VITE_APP_BASE || process.env.VITE_APP_BASE
const manifest = (await mfs.readFile(`${outDirStatic}/.vite/manifest.json`)) as string
let manifest = null

// If from build, use manifest file from _temp/
if (!isGenerate) {
manifest = await mfs.readFile(`${outDirStaticTemp}/.vite/manifest.json`)
} else {
// Else from client/
manifest = await mfs.readFile(`${outDirStatic}/.vite/manifest.json`)
}

const scriptTags = ManifestParser.getScriptTagFromManifest(manifest, base)
let errorOnRender = false
const renderPromises: Promise<void>[] = []

// pre-render each route
for (let url of urls) {
url = url.startsWith("/") ? url : `/${url}`
let formattedURL = url.startsWith("/") ? url : `/${url}`

try {
// Request DOM
const dom = await render(url, scriptTags, true, base)
const dom = await render(formattedURL, scriptTags, true, base)
// create stream and generate current file when all DOM is ready
renderToPipeableStream(dom, {
onAllReady() {
createHtmlFile(urls, url, outDirStatic, dom)
},
onError(x) {
console.error(x)
}
})
renderPromises.push(
new Promise<void>((resolve, rejects) => {
renderToPipeableStream(dom, {
onAllReady: async () => {
await createHtmlFile(urls, formattedURL, outDirStaticTemp, dom)
resolve()
},
onError(x) {
errorOnRender = true
console.error(x)
rejects(new Error("Error on renderToPipeableStream"))
}
})
})
)
} catch (e) {
console.log(e)
}
}
await Promise.all(renderPromises)

if (errorOnRender) {
console.error(chalk.red("Error on render"))
process.exit(1)
} else if (!isGenerate) {
// If from build, move whole folder
await moveFolder(outDirStatic, "dist/static/old")
await moveFolder(outDirStaticTemp, outDirStatic)
} else {
// If from generate, move html files only
await moveHTML(outDirStaticTemp, outDirStatic)
}
}

/**
Expand All @@ -71,6 +104,7 @@ const createHtmlFile = async (
if (isRouteIndex(url, urls)) url = `${url}/index`
const routePath = path.resolve(`${outDir}/${url}`)
const htmlFilePath = `${routePath}.html`

// Create file
await mfs.createFile(htmlFilePath, htmlReplacement(renderToString(dom)))
console.log(chalk.green(` → ${htmlFilePath.split("static")[1]}`))
Expand All @@ -84,3 +118,71 @@ const htmlReplacement = (render: string): string =>
.replace("<html", `<!DOCTYPE html><html`)
.replaceAll('<script nomodule=""', "<script nomodule")
.replaceAll('crossorigin="anonymous"', "crossorigin")

async function copyFile(source, destination) {
Bastou marked this conversation as resolved.
Show resolved Hide resolved
await fs.mkdir(path.dirname(destination), { recursive: true })
await fs.copyFile(source, destination)
}

async function moveFolder(source, destination) {
try {
// Crée le dossier de destination s'il n'existe pas
await fs.mkdir(destination, { recursive: true })

// Lire le contenu du dossier source
const entries = await fs.readdir(source, { withFileTypes: true })

for (const entry of entries) {
const sourcePath = path.join(source, entry.name)
const destinationPath = path.join(destination, entry.name)

if (entry.isDirectory()) {
// Appel récursif pour les sous-dossiers
await moveFolder(sourcePath, destinationPath)
} else {
// Copier le fichier
await copyFile(sourcePath, destinationPath)
await fs.unlink(sourcePath) // Supprimer le fichier source après copie
}
}

// Supprimer le dossier source après déplacement de son contenu
await fs.rmdir(source)
// console.log(`Folder ${source} moved to ${destination}`)
} catch (err) {
console.error(`Erreur lors du déplacement du dossier : ${err}`)
}
}

async function moveHTML(source: string, destination: string): Promise<void> {
try {
// Crée le dossier de destination s'il n'existe pas
await fs.mkdir(destination, { recursive: true })

// Lire le contenu du dossier source
const entries = await fs.readdir(source, { withFileTypes: true })

for (const entry of entries) {
const sourcePath = path.join(source, entry.name)
const destinationPath = path.join(destination, entry.name)

if (entry.isDirectory()) {
// Appel récursif pour les sous-dossiers
await moveHTML(sourcePath, destinationPath)
} else if (path.extname(entry.name).toLowerCase() === ".html") {
// Copier le fichier HTML
await fs.copyFile(sourcePath, destinationPath)
await fs.unlink(sourcePath) // Supprimer le fichier source après copie
// console.log(`File ${entry.name} moved from ${source} to ${destination}`)
}
}

// Vérifier si le dossier source est vide après déplacement des fichiers HTML
const remainingEntries = await fs.readdir(source)
if (remainingEntries.length === 0) {
await fs.rmdir(source) // Supprimer le dossier source s'il est vide
}
} catch (err) {
console.error(`Erreur lors du déplacement des fichiers HTML : ${err}`)
}
}
2 changes: 1 addition & 1 deletion apps/front/prerender/urls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const fetchAvailableUrls = async (): Promise<string[]> => {
"/work",
"/work/first",
"/work/second",
"/404"
"/404",
])
})
}
Loading