Files
Jorem JuárezandClaude Fable 5 6ff459a7c4 perf(frontend): pre-compila el JSX en el build (elimina babel-standalone del navegador)
Antes cada página mandaba babel-standalone (~2.7MB) y compilaba el JSX en vivo en
el navegador en cada carga. Ahora se compila en el build de Docker y se sirve JS
plano; el navegador nunca ve babel. La lógica de las páginas no cambia — solo el
empaquetado.

- frontend/build.mjs + package.json: compila el <script type="text/babel"> inline
  de las 4 páginas con @babel/preset-react (runtime clásico → React.createElement,
  idéntico a babel-standalone). NO transpila sintaxis moderna (?., async, spread):
  pasa intacta. Emite dist/ con HTML de prod + JS con hash en el nombre.
- El FUENTE (.html) conserva el JSX + babel-standalone para dev local sin build.
- Dockerfile: etapa nueva frontend-build compila; la imagen final sirve dist/.
  Babel vive solo en la etapa de build, no en la imagen.
- nginx: cache inmutable (1 año) para los .js con hash; HTML no-cache para tomar
  el hash nuevo tras cada deploy.
- .dockerignore: excluye frontend/node_modules y frontend/dist del contexto.

Primera carga: de ~2.9MB a ~150-220KB (react-dom + react + JS por página + theme).
Sin cambios en backend/src.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 19:43:31 -06:00

71 lines
3.1 KiB
JavaScript

// Build del frontend: compila el JSX inline de cada .html a JS plano y reescribe
// el HTML para que cargue ese JS ya compilado en vez de babel-standalone.
//
// - El FUENTE (.html) conserva el <script type="text/babel"> + babel-standalone,
// para que dev local siga funcionando sin build.
// - Aquí se produce dist/ con el HTML de producción + el JS compilado (con hash
// en el nombre, para cache inmutable). Esto es lo que se hornea en la imagen.
// - SOLO se aplica @babel/preset-react (runtime clásico): JSX → React.createElement,
// idéntico a babel-standalone con data-presets="react". NO transpila sintaxis
// moderna (?., async/await, spread, template literals): pasa intacta.
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { transformSync } from '@babel/core';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const DIST = path.join(__dirname, 'dist');
const PAGES = ['checada.html', 'kiosco.html', 'panel.html', 'becario.html'];
const hash8 = (buf) => crypto.createHash('sha256').update(buf).digest('hex').slice(0, 8);
fs.rmSync(DIST, { recursive: true, force: true });
fs.mkdirSync(DIST, { recursive: true });
// theme.js es JS plano (usa React.createElement, sin JSX): solo se hashea para
// poder servirlo con cache inmutable. logo-taboada.png se copia tal cual.
const themeSrc = fs.readFileSync(path.join(__dirname, 'theme.js'));
const themeName = `theme.${hash8(themeSrc)}.js`;
fs.writeFileSync(path.join(DIST, themeName), themeSrc);
fs.copyFileSync(path.join(__dirname, 'logo-taboada.png'), path.join(DIST, 'logo-taboada.png'));
// Quita el <script src=".../babel...js"> (con su indentación y salto de línea).
const RE_BABEL_LIB = /[ \t]*<script[^>]*\bsrc="[^"]*babel[^"]*"[^>]*><\/script>\r?\n?/i;
const RE_INLINE = /<script\s+type="text\/babel"[^>]*>([\s\S]*?)<\/script>/;
const RE_THEME = /<script\s+src="theme\.js"><\/script>/;
for (const page of PAGES) {
let html = fs.readFileSync(path.join(__dirname, page), 'utf8');
const m = html.match(RE_INLINE);
if (!m) throw new Error(`${page}: no se encontró <script type="text/babel">`);
const out = transformSync(m[1], {
presets: [['@babel/preset-react', { runtime: 'classic' }]],
filename: page,
babelrc: false,
configFile: false,
compact: false,
comments: true,
});
if (!out || typeof out.code !== 'string') throw new Error(`${page}: babel no devolvió código`);
const base = page.replace(/\.html$/, '');
const jsName = `${base}.${hash8(out.code)}.js`;
fs.writeFileSync(path.join(DIST, jsName), out.code);
html = html
.replace(RE_BABEL_LIB, '')
.replace(RE_THEME, `<script src="${themeName}"></script>`)
.replace(RE_INLINE, `<script src="${jsName}"></script>`);
if (/babel/i.test(html)) throw new Error(`${page}: el HTML aún referencia babel tras compilar`);
fs.writeFileSync(path.join(DIST, page), html);
console.log(`✓ ${page.padEnd(13)} → ${jsName} (${(out.code.length / 1024).toFixed(1)} KB)`);
}
console.log(`✓ theme → ${themeName}`);
console.log('Frontend compilado en dist/ — sin babel en el navegador.');