Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ _Start your static projects in seconds with an optimized architecture_
| Feature | Description |
| ----------------------------- | ---------------------------------------------- |
| 🚀 **Fast generation** | Project creation with a single command |
| 🔄 **Hot Reloading** | Automatic reload during development |
| 🔥 **Smart Hot Reload** | Intelligent rebuild with targeted updates |
| 📦 **Optimized build** | Production-optimized bundle |
| 🎯 **Targeted revalidation** | Specific page reconstruction via API |
| 🛠️ **Flexible configuration** | Advanced customization according to your needs |
Expand Down
38 changes: 38 additions & 0 deletions helpers/buildDev.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { exec } from "child_process";
import { promisify } from "util";
import path from "path";

const execAsync = promisify(exec);

interface BuildOptions {
specificFiles?: string[];
verbose?: boolean;
}

export async function buildDev(options: BuildOptions = {}) {
const { specificFiles = [], verbose = false } = options;

try {
const start = Date.now();

if (verbose) {
console.log('[staticjs] Starting development build...');
if (specificFiles.length > 0) {
console.log('[staticjs] Changed files:', specificFiles.map(f => path.basename(f)).join(', '));
}
}

// Use the bt-staticjs build command directly
await execAsync('bt-staticjs build');

const duration = Date.now() - start;
if (verbose) {
console.log(`[staticjs] Build completed in ${duration}ms`);
}

return { success: true, duration };
} catch (error) {
console.error('[staticjs] Build failed:', error);
return { success: false, error: error instanceof Error ? error.message : String(error) };
}
}
87 changes: 87 additions & 0 deletions helpers/createPageDev.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import fs from "fs";
import path from "path";
import React from "react";
import ReactDOMServer from "react-dom/server";

const outputDir = path.resolve(process.cwd(), "dist");

interface IcreatePageDev {
data: any,
AppComponent: React.FC<{ Component: React.FC; props: {} }>,
PageComponent: () => React.JSX.Element,
initialDatasId: string,
rootId: string,
pageName: string,
JSfileName: string | false,
isDev?: boolean,
}

export const createPageDev = ({
data,
AppComponent,
PageComponent,
initialDatasId,
rootId,
pageName,
JSfileName,
isDev = false,
}: IcreatePageDev) => {
// Hot reload script for development
const hotReloadScript = isDev ? `
<script type="module">
// Hot reload client for StaticJS
const ws = new WebSocket('ws://localhost:3300');

ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'full-reload') {
console.log('[staticjs] 🔄 Hot reloading...');
window.location.reload();
}
};

ws.onopen = () => {
console.log('[staticjs] 🔥 Hot reload connected');
};

ws.onclose = () => {
console.log('[staticjs] ❌ Hot reload disconnected');
// Attempt reconnection after 1 second
setTimeout(() => {
window.location.reload();
}, 1000);
};

ws.onerror = (error) => {
console.log('[staticjs] ⚠️ Hot reload error:', error);
};
</script>` : '';

const template = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>StaticJS App</title>
</head>
<body>
<div id="app-{{rootId}}">{{html}}</div>
${data ? `<script id="initial-data-{{initialDatasId}}" type="application/json">${JSON.stringify(data)}</script>` : ""}
${JSfileName ? `<script type="module" src="{{scriptPath}}"></script>` : ""}
${hotReloadScript}
</body>
</html>`;

const component = React.createElement(AppComponent, {
Component: PageComponent,
props: { data },
});

const htmlContent = template
.replace("{{initialDatasId}}", initialDatasId)
.replace("{{rootId}}", rootId)
.replace("{{html}}", ReactDOMServer.renderToString(component))
.replace("{{scriptPath}}", `${JSfileName}.js`);

fs.writeFileSync(path.join(outputDir, `${pageName}.html`), htmlContent);
};
25 changes: 24 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"bin": {
"create-staticjs-app": "./dist/scripts/create-static-app.js",
"bt-staticjs": "./dist/scripts/cli.js",
"bt-staticjs-dev": "./dist/scripts/cli-dev.js",
"generate-test-multiapps": "./dist/scripts/generate-test-multiapps.js"
},
"scripts": {
Expand Down
109 changes: 109 additions & 0 deletions scripts/build-html-dev.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

import fs from "fs/promises";
import crypto from "node:crypto";
import path from "path";
import { createPageDev } from "../helpers/createPageDev.js";

const rootDir = path.resolve(process.cwd(), "./src");

async function loadJson(filePath: string) {
const data = await fs.readFile(filePath, "utf-8");
return JSON.parse(data);
}

async function main() {
const excludedJSFiles = await loadJson(
path.join(path.resolve(process.cwd()), "./cache/excludedFiles.json")
);
const files = await loadJson(
path.join(path.resolve(process.cwd()), "./cache/pagesCache.json")
);

const processPage = async (page: { path: string; pageName: string }) => {
try {
let data;
const absolutePath = page.path;
const pageModule = await import(absolutePath);
const appModule = await import(`${rootDir}/app.tsx`);
const fileName = path.basename(page.path, path.extname(page.path));

const AppComponent = appModule.App;
const PageComponent = pageModule.default;
const getStaticProps = pageModule?.getStaticProps;
const getStaticPaths = pageModule?.getStaticPaths;
const injectJS = !excludedJSFiles.includes(page.pageName);

const rootId = crypto
.createHash("sha256")
.update(`app-${absolutePath}`)
.digest("hex")
.slice(0, 10);

const initialDatasId = crypto
.createHash("sha256")
.update(`initial-data-${absolutePath}`)
.digest("hex")
.slice(0, 10);

if (!PageComponent) {
throw new Error(
`Failed to import PageComponent from ${page.pageName}.tsx`
);
}

if (getStaticProps && getStaticPaths) {
const { paths } = await getStaticPaths();
return paths.forEach(
async (param: { params: { [x: string]: string } }) => {
const slug = param.params[fileName.replace(/[\[\]]/g, "")];
const { props } = await getStaticProps(param);
const pageName = page.pageName.replace(/\[.*?\]/, slug);
const JSfileName =
injectJS && fileName.replace(/\[(.*?)\]/g, "_$1_");

createPageDev({
data: props.data,
AppComponent,
PageComponent,
initialDatasId,
rootId,
pageName,
JSfileName: JSfileName,
isDev: true, // Mode développement
});
}
);
}

if (getStaticProps) {
const { props } = await getStaticProps();
data = props.data;
}

createPageDev({
data,
AppComponent,
PageComponent,
initialDatasId,
rootId,
pageName: page.pageName,
JSfileName: injectJS && fileName,
isDev: true, // Mode développement
});

console.log(`Successfully wrote: dist/${page.pageName}.html (with hot reload)`);
} catch (error) {
console.error(`Error processing ${page.pageName}:`, error);
}
};

const pages = Object.entries(files).map(([pageName, path]) => ({
pageName: pageName as string,
path: path as string,
}));

pages.forEach(processPage);
}

main();
47 changes: 47 additions & 0 deletions scripts/cli-dev.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#!/usr/bin/env node

import { program } from "commander";
import { execSync } from "node:child_process";
import { dirname } from "node:path";
import { fileURLToPath } from "node:url";
import path from "path";

const __dirname = dirname(fileURLToPath(import.meta.url));

program
.command("build-dev")
.description("Build with static.js configuration for development (with hot reload)")
.action(() => {
try {
const cachePagesPath = path.resolve(
__dirname,
"../helpers/cachePages.js"
);

const htmlConfigDev = path.resolve(__dirname, "./build-html-dev.js");
const dest = process.cwd();
console.log("Executing static.js dev config...");

execSync("rimraf dist", {
cwd: dest,
stdio: "inherit",
});

execSync(`rimraf cache && node ${cachePagesPath}`, {
cwd: dest,
stdio: "inherit",
});

execSync(`vite build && tsx ${htmlConfigDev}`, {
cwd: dest,
stdio: "inherit",
});

console.log("Dev build completed successfully with hot reload");
} catch (error) {
console.error("Dev build failed:", error);
process.exit(1);
}
});

program.parse(process.argv);
Loading