Configurare un progetto
Una vista è una normale pagina web che qualsiasi configurazione di build per il web può produrre. Le tre configurazioni complete qui sotto elencano tutti i file da creare: una sola pagina HTML (niente da installare), Vite con JavaScript semplice e Vite con React. Ognuna costruisce la vista dell'Avvio rapido che gira qui sotto. Abbiamo costruito ogni configurazione esattamente come è scritta qui e l'abbiamo aperta in un browser.
Dove sta il kit
Le due configurazioni Vite installano il pacchetto @unaiverse/gui-kit (Installazione) e caricano il kit con una riga:
import { connectToHost } from '@unaiverse/gui-kit';Una pagina HTML sola non ha un bundler che risolva il nome di un pacchetto. Usa quindi il file scaricato unaiverse-gui.js con i suoi tipi accanto alla pagina (Installazione) e lo importa con il suo percorso ('./unaiverse-gui.js'). In tutti e due i casi l'import è un import standard di un modulo ES e il kit è un modulo del tuo progetto come tutti gli altri:
- In una pagina semplice il file sta accanto alla tua pagina e il browser lo scarica dal tuo sito all'avvio della pagina.
- In Vite
npm installmette il kit innode_modulese Vite lo mette nel bundle con il resto del tuo codice.npm run devlo serve enpm run buildlo scrive nei file costruiti. I tuoi visitatori lo scaricano dal tuo sito e da UNaIVERSE non arriva niente.
Una sola pagina HTML
La configurazione più rapida ha un solo file e non richiede né build né installazione. È adatta alle viste piccole e ai prototipi.
my-view/
index.html
unaiverse-gui.js
unaiverse-gui.d.ts<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Arena</title>
</head>
<body>
<!-- type="module": the kit is an ES module, and this allows `import` and top-level `await`. -->
<script type="module">
import { connectToHost } from './unaiverse-gui.js';
// A fake world to build with: no account, no network.
const arena = {
name: 'Arena',
now: { text: 'Waiting for players' },
onMessage: (message) => `Hello! You said: ${message.text}`,
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });
// The page: a title, what is happening, a button, the last answer of the world.
const title = document.createElement('h1');
const now = document.createElement('p');
const button = document.createElement('button');
const answer = document.createElement('p');
button.textContent = 'Say hello';
button.onclick = () => world.send('hello');
document.body.append(title, now, button, answer);
// Called at once, then after every change of the world.
world.subscribe((node) => {
title.textContent = node.name;
now.textContent = node.now?.text ?? '';
const last = node.messages.filter((message) => !message.fromMe).at(-1);
answer.textContent = last ? last.text : 'No answer yet.';
});
</script>
</body>
</html>Avviala. Servi la cartella con un server web locale qualsiasi e apri l'indirizzo che stampa:
cd my-view
npx serve # then open http://localhost:3000
# or, with Python:
python3 -m http.server 8000 # then open http://localhost:8000Una pagina aperta come file (con un doppio clic su index.html) non riesce a caricare il kit (Installazione).
Quando cresce, lo script può passare a un file suo main.js accanto a unaiverse-gui.js e caricarsi con <script type="module" src="./main.js"></script>. La riga che importa il kit resta la stessa.
Vite con JavaScript semplice
Vite dà alla tua vista i pacchetti npm, una build di produzione e un server di sviluppo che ricarica la pagina a ogni salvataggio. Il progetto Vite più piccolo per una vista ha questi file:
my-view/
package.json
index.html
src/
main.js{
"name": "my-view",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@unaiverse/gui-kit": "^1.0.0"
},
"devDependencies": {
"vite": "^8.3.6"
}
}Vite parte da index.html e segue il suo tag <script> fino a src/main.js:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Arena</title>
</head>
<body>
<script type="module" src="/src/main.js"></script>
</body>
</html>src/main.js è la vista dell'Avvio rapido:
import { connectToHost } from '@unaiverse/gui-kit';
// A fake world to build with: no account, no network.
const arena = {
name: 'Arena',
now: { text: 'Waiting for players' },
onMessage: (message) => `Hello! You said: ${message.text}`,
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });
// The page: a title, what is happening, a button, the last answer of the world.
const title = document.createElement('h1');
const now = document.createElement('p');
const button = document.createElement('button');
const answer = document.createElement('p');
button.textContent = 'Say hello';
button.onclick = () => world.send('hello');
document.body.append(title, now, button, answer);
// Called at once, then after every change of the world.
world.subscribe((node) => {
title.textContent = node.name;
now.textContent = node.now?.text ?? '';
const last = node.messages.filter((message) => !message.fromMe).at(-1);
answer.textContent = last ? last.text : 'No answer yet.';
});Avvialo:
cd my-view
npm install
npm run dev # then open http://localhost:5173
npm run build # writes the finished view into dist/
npm run preview # serves dist/, to try the buildVite 6 o precedenti
Vite 7 e le versioni successive fanno la build del await di primo livello di main.js così com'è. Con Vite 6 o precedenti npm run build si ferma con "Top-level await is not available in the configured target environment" e richiede questo vite.config.js accanto a package.json:
import { defineConfig } from 'vite';
// Build for browsers that support top-level await (every current browser does).
export default defineConfig({
build: { target: 'es2022' },
});Vite con React
La stessa vista con React richiede React, Vite e il plugin React per Vite:
my-view/
package.json
vite.config.js
index.html
src/
main.jsx
App.jsx
useWorld.js{
"name": "my-view",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@unaiverse/gui-kit": "^1.0.0",
"react": "^19.3.1",
"react-dom": "^19.3.1"
},
"devDependencies": {
"@vitejs/plugin-react": "^6.2.1",
"vite": "^8.3.6"
}
}vite.config.js attiva il plugin React e non richiede nessuna voce per il kit:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// The React plugin turns your .jsx files into JavaScript.
// The kit needs nothing here: Vite finds the package in node_modules like any other.
export default defineConfig({
plugins: [react()],
});index.html contiene l'elemento in cui React fa il render:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Arena</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>src/main.jsx avvia React con createRoot:
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';
// Draws your view into <div id="root"> of index.html.
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>,
);src/App.jsx è la vista React dell'Avvio rapido:
import { useWorld } from './useWorld.js';
// A fake world to build with: no account, no network.
const arena = {
name: 'Arena',
now: { text: 'Waiting for players' },
onMessage: (message) => `Hello! You said: ${message.text}`,
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: arena } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
const last = world.messages.filter((message) => !message.fromMe).at(-1);
return (
<>
<h1>{world.name}</h1>
<p>{world.now?.text}</p>
<button onClick={() => world.send('hello')}>Say hello</button>
<p>{last ? last.text : 'No answer yet.'}</p>
</>
);
}src/useWorld.js è l'hook che usa ogni vista React. Si connette una volta e fa il re-render del tuo componente a ogni cambiamento del mondo. È anche l'unico file che importa il kit. Copialo così com'è (useWorld):
// useWorld.js: copy this file next to your React components.
// It connects your view to the world it is for and keeps your component up
// to date by rendering it again at every change of the world.
import { useEffect, useState } from 'react';
import { connectToHost } from '@unaiverse/gui-kit';
/**
* Gives a React component the world its view is for.
*
* - `world` is null until the world arrives, then the newest world after every change.
* - `error` holds the error when the view cannot connect (its `code` says why, for example 'no-host').
*
* Pass `{ fake: { world: { ... } } }` while you build (no account, no network),
* and nothing in the webapp.
*
* @param {object} [options] - What `connectToHost` takes, for example `{ fake: { world } }`.
* @returns {{ world: object | null, error: Error | null }}
*/
export function useWorld(options) {
const [state, setState] = useState({ world: null, error: null });
useEffect(() => {
let isActive = true;
let stop = () => {};
connectToHost(options)
.then((world) => {
if (!isActive) return;
// Called at once, then after every change of the world.
stop = world.subscribe((next) => setState({ world: next, error: null }));
})
.catch((error) => {
if (isActive) setState({ world: null, error });
});
return () => {
isActive = false;
stop();
};
// Connect once, when the component appears.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return state;
}Avvialo con gli stessi comandi di prima: npm install, npm run dev, npm run build.
Strict mode
In sviluppo lo StrictMode di React esegue due volte ogni effetto per far emergere i bug. useWorld ferma la prima connessione nel cleanup del suo effetto e tiene la seconda. Nella vista costruita gli effetti girano una volta sola.
TypeScript
I template TypeScript di Vite funzionano allo stesso modo con la stessa riga di import. TypeScript legge i tipi del pacchetto in node_modules e trova da solo unaiverse-gui.d.ts accanto a un unaiverse-gui.js scaricato. Il completamento nell'editor spiega come escludere il file del kit dai controlli dei tipi.
Metterla online
Ogni configurazione produce file semplici da mettere online (index.html per la pagina sola e la cartella dist/ per Vite). Prima di caricarli:
- togli il mondo finto chiamando
connectToHost()ouseWorld()senza argomenti - servili in HTTPS dal tuo server con l'header che permette alla webapp di mostrarli in un iframe (Andare online lo riporta per nginx, Apache ed Express)
- per una vista in una sottocartella come
https://your.site/views/arena/scrivibase: './'invite.config.jsperché altrimenti Vite scrive gli indirizzi a partire dalla radice del sito (/assets/...).
Poi scrivi l'indirizzo della tua vista nel campo Vista propria del tuo mondo (Andare online).
Che cosa abbiamo controllato
Il 6 novembre 2026 abbiamo costruito dai loro file tutte le configurazioni qui sopra con Vite 8.3.6, React 19.3.1 e @vitejs/plugin-react 6.2.1 e le abbiamo aperte una per una in un browser headless. Abbiamo servito la pagina sola con python3 -m http.server e le due configurazioni Vite con npm run dev e dopo npm run build. Ogni configurazione girava sul mondo finto con il kit caricato dal progetto. Il pulsante riceveva la sua risposta e nessuna richiesta arrivava a UNaIVERSE. In quella prova le due configurazioni Vite importavano il file scaricato da src/ al posto del pacchetto. Il pacchetto contiene lo stesso file. Vite 6.4.5 ha fatto la build della configurazione in JavaScript semplice con build.target uguale a 'es2022'.
Prossimi passi
- Pensare per viste: le idee alla base di ogni vista in qualsiasi configurazione.
- Tutorial: la vista di un mondo: una vista completa costruita un passo alla volta.
- Installazione: il completamento dei nomi del kit nel tuo editor.