bro.landing/scripts/ssr-prerender.js

80 lines
2.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* eslint-disable @typescript-eslint/no-require-imports */
/* eslint-disable no-undef */
/* eslint-disable @typescript-eslint/no-unused-vars */
const fs = require('fs');
const path = require('path');
const { JSDOM } = require('jsdom');
// Настройка окружения для SSR
const setupDOM = () => {
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', {
url: 'http://localhost',
pretendToBeVisual: true,
resources: 'usable'
});
global.window = dom.window;
global.document = dom.window.document;
global.navigator = dom.window.navigator;
global.HTMLElement = dom.window.HTMLElement;
global.HTMLDivElement = dom.window.HTMLDivElement;
global.requestAnimationFrame = (callback) => setTimeout(callback, 0);
global.cancelAnimationFrame = clearTimeout;
};
const cleanupRender = () => {
delete global.window;
delete global.document;
delete global.navigator;
delete global.HTMLElement;
delete global.HTMLDivElement;
delete global.requestAnimationFrame;
delete global.cancelAnimationFrame;
};
const prerender = async () => {
try {
console.log('🚀 Начинаем SSR пре-рендеринг...');
setupDOM();
// Читаем HTML шаблон
const indexPath = path.resolve(__dirname, '../dist/index.html');
let html = fs.readFileSync(indexPath, 'utf-8');
// Рендерим статический контент страницы "в разработке"
const prerenderContent = `
<div style="text-align: center; padding: 20px;">
<div style="max-height: 250px; margin: 0 auto;">
<div>⚙️</div>
</div>
<h3><center>Сайт в разработке</center></h3>
<p style="color: #666;">Страница загружается...</p>
</div>
`.trim();
// Вставляем пре-рендеренный контент в div#app
const searchString = '<div id="app"></div>';
if (html.includes(searchString)) {
html = html.replace(searchString, `<div id="app">${prerenderContent}</div>`);
// Сохраняем результат
fs.writeFileSync(indexPath, html, 'utf-8');
console.log('✅ SSR пре-рендеринг завершен успешно!');
console.log('📄 HTML обновлен с серверным контентом');
} else {
console.log('⚠️ Не найден <div id="app"></div>');
console.log('Возможно, HTML уже содержит пре-рендеренный контент');
}
cleanupRender();
} catch (error) {
console.error('❌ Ошибка при SSR пре-рендеринге:', error);
cleanupRender();
process.exit(1);
}
};
prerender();