Fase 0/1 migración a TSX: islas React con Vite + API JSON (piloto: noticias)

Arquitectura elegida: islas React/TSX montadas sobre las plantillas Django
existentes (django-vite), alimentadas por endpoints JSON bajo /api/. El backend,
las URLs y la auth por sesión se mantienen; se migra sección a sección.

Fase 0 (tooling):
- frontend/ con Vite + React 18 + TypeScript. Build a static/dist con manifest.
- django-vite 3.1 en INSTALLED_APPS + DJANGO_VITE (dev_mode=DEBUG,
  static_url_prefix='dist'). STATIC_URL pasa a '/static/' (absoluto) para que los
  assets no choquen con el <base href> de la plantilla. WhiteNoise sirve el bundle.
- .gitignore: frontend/node_modules y static/dist (artefactos de build).

Fase 1 (piloto: lista de noticias de la portada):
- API: home/views/api.py -> home_news_api (JsonResponse); ruta /api/home/news/
  montada en home/api_urls.py fuera de i18n_patterns.
- React: NewsList.tsx hace fetch de la API y renderiza las noticias (mismas clases
  CSS que el HTML original). Entry src/entries/home.tsx monta en #home-news-app.
- partials/noticias.html: el bucle {% for noticia %} se reemplaza por el contenedor
  de montaje + {% vite_asset %}.

Verificado en producción: manage.py check OK, /api/home/news/ 200, la home incluye
el mount y el <script> del bundle, y el bundle se sirve (200).

Build en deploy: cd frontend && npm run build && collectstatic (ver frontend/README.md).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-12 20:18:35 +00:00
parent 1ee126a69f
commit 98c3cbdbc6
16 changed files with 1978 additions and 20 deletions
+4
View File
@@ -6,3 +6,7 @@ home/migrations/__pycache__
**/__pycache__/*.pyc
.venv/
.env
# Frontend (Vite / React islands)
frontend/node_modules/
static/dist/
+32
View File
@@ -0,0 +1,32 @@
# Frontend NovaWoW (islas React/TSX con Vite)
Migración incremental de las plantillas HTML de Django a componentes React/TSX,
montados como **islas** sobre las páginas que sigue sirviendo Django. Los datos se
obtienen de endpoints JSON bajo `/api/` (ver `home/api_urls.py`).
## Estructura
- `src/entries/*.tsx` — puntos de entrada de Vite; cada uno monta una isla en un
contenedor que deja la plantilla Django (p. ej. `#home-news-app`).
- `src/components/*.tsx` — componentes React.
- `vite.config.ts` — build a `../static/dist` con manifest (base `/static/dist/`).
La plantilla carga la isla con `{% load django_vite %}` + `{% vite_asset 'src/entries/xxx.tsx' %}`.
## Desarrollo (con HMR)
Requiere `DJANGO_DEBUG=True`. En un terminal:
```
cd frontend && npm install && npm run dev
```
django-vite (dev_mode = DEBUG) inyecta el cliente HMR y sirve desde el dev server.
## Producción (build)
Con `DJANGO_DEBUG=False`, Django sirve el bundle construido vía manifest. Tras
cualquier cambio en `frontend/`:
```
cd /root/NovaWoW/frontend && npm run build # genera ../static/dist + manifest
cd /root/NovaWoW && .venv/bin/python manage.py collectstatic --noinput
systemctl restart novawow
```
Los artefactos (`node_modules/`, `static/dist/`) están en `.gitignore`: se regeneran
con `npm run build`.
+1729
View File
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "novawow-frontend",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.4",
"typescript": "^5.6.3",
"vite": "^6.0.7"
}
}
+78
View File
@@ -0,0 +1,78 @@
import { useEffect, useState } from 'react'
import type { Noticia } from '../types'
function formatFecha(iso: string | null): string {
if (!iso) return ''
const d = new Date(iso)
if (isNaN(d.getTime())) return iso
return d.toLocaleString('es-ES', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
})
}
export function NewsList() {
const [noticias, setNoticias] = useState<Noticia[] | null>(null)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
let cancelled = false
fetch('/api/home/news/', { headers: { Accept: 'application/json' } })
.then((r) => {
if (!r.ok) throw new Error(`HTTP ${r.status}`)
return r.json()
})
.then((data: { noticias: Noticia[] }) => {
if (!cancelled) setNoticias(data.noticias)
})
.catch((e) => {
if (!cancelled) setError(String(e))
})
return () => {
cancelled = true
}
}, [])
if (error) {
return <p>No se pudieron cargar las noticias.</p>
}
if (noticias === null) {
return <p>Cargando noticias</p>
}
if (noticias.length === 0) {
return <p>No hay noticias disponibles en este momento.</p>
}
return (
<>
{noticias.map((n) => (
<div key={n.id} className="noticia-item">
<h3>{n.titulo}</h3>
<span className="date">{formatFecha(n.fecha)}</span>
<div
className="noticia-contenido"
dangerouslySetInnerHTML={{ __html: n.contenido }}
/>
{n.enlace && (
<p>
Enlace:{' '}
<a href={n.enlace} target="_blank" rel="noopener noreferrer">
aquí
</a>
</p>
)}
<br />
<hr />
<br />
</div>
))}
<p className="centered third-brown">
<i>* Mostrando las últimas 50 noticias</i>
</p>
<br />
</>
)
}
+14
View File
@@ -0,0 +1,14 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { NewsList } from '../components/NewsList'
// Isla de la portada: monta la lista de noticias (React) donde Django deja
// el contenedor #home-news-app. El resto de la página sigue siendo Django.
const el = document.getElementById('home-news-app')
if (el) {
createRoot(el).render(
<StrictMode>
<NewsList />
</StrictMode>,
)
}
+7
View File
@@ -0,0 +1,7 @@
export interface Noticia {
id: number
titulo: string
fecha: string | null
contenido: string
enlace: string | null
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+21
View File
@@ -0,0 +1,21 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { resolve } from 'node:path'
// El bundle se construye en ../static/dist (que está en STATICFILES_DIRS),
// con manifest para que django-vite resuelva los assets en producción.
// base '/static/dist/' → coincide con static_url_prefix='dist' de django-vite.
export default defineConfig({
plugins: [react()],
base: '/static/dist/',
build: {
manifest: true,
outDir: resolve(__dirname, '../static/dist'),
emptyOutDir: true,
rollupOptions: {
input: {
home: resolve(__dirname, 'src/entries/home.tsx'),
},
},
},
})
+7
View File
@@ -0,0 +1,7 @@
"""Rutas de la API JSON (islas React). Se montan bajo /api/ fuera de i18n_patterns."""
from django.urls import path
from . import views
urlpatterns = [
path('home/news/', views.home_news_api, name='api_home_news'),
]
+6 -19
View File
@@ -1,4 +1,5 @@
<!-- main -->
{% load django_vite %}
<!-- main -->
<div class="main-page">
<div class="middle-content middle-content-index">
<div class="body-content">
@@ -60,24 +61,10 @@
</div>
<div class="box-content">
<div class="body-box-content">
{% for noticia in noticias %}
<h3>{{ noticia.titulo }}</h3>
<span class="date">{{ noticia.fecha_publicacion }}</span>
<div class="noticia-contenido">
{{ noticia.contenido|safe }}
</div>
{% if noticia.enlace %}
<p>Enlace: <a href="{{ noticia.enlace }}" target="_blank" rel="noopener noreferrer">aquí</a></p>
{% endif %}
<br />
<hr />
<br />
{% empty %}
<p>No hay noticias disponibles en este momento.</p>
{% endfor %}
<p class="centered third-brown"><i>* Mostrando las últimas 50 noticias</i></p>
<br />
<!-- Isla React (Vite): la lista de noticias se renderiza en TSX y se
alimenta del endpoint /api/home/news/. Migrado desde el bucle Django. -->
<div id="home-news-app"></div>
{% vite_asset 'src/entries/home.tsx' %}
</div>
</div>
+1
View File
@@ -16,3 +16,4 @@ from .guild import * # noqa: F401,F403
from .history import * # noqa: F401,F403
from .players import * # noqa: F401,F403
from .payments import * # noqa: F401,F403
from .api import * # noqa: F401,F403
+21
View File
@@ -0,0 +1,21 @@
from ._base import *
# Endpoints JSON que alimentan las islas React/TSX del frontend (Vite).
# Se montan bajo /api/ (fuera de i18n_patterns). De momento con JsonResponse;
# si crece la superficie de la API se puede introducir DRF.
def home_news_api(request):
"""Últimas noticias para la isla de la portada."""
noticias = Noticia.objects.order_by('-fecha_publicacion')[:50]
data = [
{
"id": n.id,
"titulo": n.titulo,
"fecha": n.fecha_publicacion.isoformat() if n.fecha_publicacion else None,
"contenido": n.contenido,
"enlace": n.enlace or None,
}
for n in noticias
]
return JsonResponse({"noticias": data})
+13 -1
View File
@@ -76,6 +76,7 @@ INSTALLED_APPS = [
'django_extensions',
'wotlk_db',
'forum',
'django_vite',
]
# Configuración para AC SOAP
@@ -276,9 +277,20 @@ USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/
STATIC_URL = 'static/'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# --- Integración con Vite (islas React/TSX) ---
# En producción (DEBUG=False) se sirve el bundle construido vía manifest;
# en desarrollo (DEBUG=True) se usa el dev server de Vite con HMR.
DJANGO_VITE = {
"default": {
"dev_mode": DEBUG,
"static_url_prefix": "dist",
"manifest_path": os.path.join(BASE_DIR, "static", "dist", ".vite", "manifest.json"),
}
}
# Directorios adicionales donde buscar archivos estáticos
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
+1
View File
@@ -8,6 +8,7 @@ from django.conf.urls.static import static
urlpatterns = [
path('', redirect_to_spanish), # Redirige la raíz a `/es/`
path('i18n/', include('django.conf.urls.i18n')), # URL para cambiar el idioma
path('api/', include('home.api_urls')), # API JSON de las islas React (sin prefijo i18n)
]
urlpatterns += i18n_patterns(
+1
View File
@@ -17,3 +17,4 @@ python-dotenv==1.2.2
gunicorn==26.0.0
nh3==0.3.6
whitenoise
django-vite