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:
@@ -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`.
|
||||
Generated
+1729
File diff suppressed because it is too large
Load Diff
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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 />
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -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>,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export interface Noticia {
|
||||
id: number
|
||||
titulo: string
|
||||
fecha: string | null
|
||||
contenido: string
|
||||
enlace: string | null
|
||||
}
|
||||
@@ -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"]
|
||||
}
|
||||
@@ -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'),
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user