vitral 0.11.1 → 0.11.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +185 -250
- package/dist/next-server.d.ts +1 -1
- package/dist/sw.d.ts +2 -2
- package/package.json +7 -3
package/README.md
CHANGED
|
@@ -20,9 +20,11 @@
|
|
|
20
20
|
<a href="./README.en.md">English</a>
|
|
21
21
|
</p>
|
|
22
22
|
|
|
23
|
-
|
|
23
|
+
Micro-frontends com qualquer framework, sem configurar build no host. React, Next.js, Vue, Nuxt, Angular, Svelte e outros na mesma página.
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
**O que é:** um micro-frontend é um pedaço da página que uma equipe constrói e publica sozinha, como o carrinho, a busca ou a área do cliente. O vitral junta esses pedaços numa página só, mesmo que cada um use um framework diferente.
|
|
26
|
+
|
|
27
|
+
**Como funciona:** cada equipe gera o seu pedaço (um *remote*) com `vite build` e publica num CDN. A página principal (o *host*) recebe a URL de cada remote e monta tudo no navegador.
|
|
26
28
|
|
|
27
29
|
**Por que usar:**
|
|
28
30
|
|
|
@@ -33,6 +35,8 @@ Cada equipe publica o próprio pedaço da página (um remote) com `vite build`.
|
|
|
33
35
|
- **Seguro.** O JS só roda se vier de uma origem permitida e se o hash SHA-384 bater.
|
|
34
36
|
- **Leve e rápido.** 5,1 kB de host. Abre a página na metade do tempo do Module Federation e troca de área 4,5 vezes mais rápido que o Next.js Multi-Zones.
|
|
35
37
|
|
|
38
|
+
**Quando usar:** quando várias equipes mexem no mesmo site e cada uma quer publicar no próprio ritmo. Com uma equipe e um app só, um bundle comum é mais simples.
|
|
39
|
+
|
|
36
40
|
```bash
|
|
37
41
|
npm install vitral
|
|
38
42
|
```
|
|
@@ -84,7 +88,7 @@ Os 10 frameworks têm testes de ponta a ponta no CI, com host e remote de framew
|
|
|
84
88
|
|
|
85
89
|
Para gerar host e remote prontos: `npm create vitral@latest`.
|
|
86
90
|
|
|
87
|
-
**1. No remote**, exporte o componente e
|
|
91
|
+
**1. No remote**, exporte o componente e ligue o plugin:
|
|
88
92
|
|
|
89
93
|
```jsx
|
|
90
94
|
// src/App.jsx (ou .vue, .svelte, .tsx…)
|
|
@@ -99,92 +103,30 @@ import vitral from 'vitral/vite'
|
|
|
99
103
|
export default { plugins: [react(), vitral()] }
|
|
100
104
|
```
|
|
101
105
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
`vite build` gera o JS, o CSS e um `vitral.json`. Publique a pasta `dist` em qualquer CDN com CORS.
|
|
106
|
+
`vite build` gera o JS, o CSS e um `vitral.json`. Publique a pasta `dist` em qualquer CDN.
|
|
105
107
|
|
|
106
|
-
**2. No host**, registre a URL e
|
|
108
|
+
**2. No host**, registre a URL e mostre o remote:
|
|
107
109
|
|
|
108
110
|
```jsx
|
|
109
111
|
import { configure } from 'vitral'
|
|
110
112
|
import { Remote } from 'vitral/react'
|
|
111
113
|
|
|
112
|
-
configure({
|
|
113
|
-
remotes: { carrinho: 'https://cdn.empresa.com/carrinho/vitral.json' },
|
|
114
|
-
})
|
|
114
|
+
configure({ remotes: { carrinho: 'https://cdn.empresa.com/carrinho/vitral.json' } })
|
|
115
115
|
|
|
116
116
|
export function App() {
|
|
117
|
-
return
|
|
118
|
-
<Remote
|
|
119
|
-
name="carrinho"
|
|
120
|
-
props={{ userId: 42 }}
|
|
121
|
-
fallback={<p>Carregando…</p>}
|
|
122
|
-
error={(erro, tentarDeNovo) => <button onClick={tentarDeNovo}>Tentar de novo</button>}
|
|
123
|
-
/>
|
|
124
|
-
)
|
|
117
|
+
return <Remote name="carrinho" props={{ userId: 42 }} fallback={<p>Carregando…</p>} />
|
|
125
118
|
}
|
|
126
119
|
```
|
|
127
120
|
|
|
128
121
|
Pronto. Mudar `props` atualiza o remote sem remontar.
|
|
129
122
|
|
|
130
|
-
|
|
123
|
+
Numa página HTML qualquer, sem build:
|
|
131
124
|
|
|
132
125
|
```html
|
|
133
126
|
<script type="module" src="https://cdn.jsdelivr.net/npm/vitral/dist/auto.js"></script>
|
|
134
127
|
<vitral-remote src="https://cdn.empresa.com/carrinho/vitral.json"></vitral-remote>
|
|
135
128
|
```
|
|
136
129
|
|
|
137
|
-
Todos os componentes de host aceitam `src` no lugar de `name`.
|
|
138
|
-
|
|
139
|
-
## Rodar local
|
|
140
|
-
|
|
141
|
-
Cada remote roda no próprio `vite dev`, numa porta. O host aponta para essas portas:
|
|
142
|
-
|
|
143
|
-
```bash
|
|
144
|
-
cd carrinho && npm run dev # vite --port 5174
|
|
145
|
-
cd busca && npm run dev # vite --port 5175
|
|
146
|
-
cd loja && npm run dev # vite --port 3000
|
|
147
|
-
```
|
|
148
|
-
|
|
149
|
-
```json
|
|
150
|
-
// loja/public/remotes.json
|
|
151
|
-
{
|
|
152
|
-
"carrinho": "http://localhost:5174/vitral.json",
|
|
153
|
-
"busca": "http://localhost:5175/vitral.json"
|
|
154
|
-
}
|
|
155
|
-
```
|
|
156
|
-
|
|
157
|
-
```js
|
|
158
|
-
// loja/src/main.jsx
|
|
159
|
-
configure({ remotes: '/remotes.json' })
|
|
160
|
-
```
|
|
161
|
-
|
|
162
|
-
Editar o remote atualiza o host sem recarregar a página (HMR). Para rodar só um remote local e pegar os outros de homologação, abra o host com `?vitral=carrinho@http://localhost:5174`.
|
|
163
|
-
|
|
164
|
-
## Docker e Kubernetes
|
|
165
|
-
|
|
166
|
-
Cada remote vira uma imagem nginx com o `dist`. O host lê a lista de remotes de uma variável de ambiente quando o contêiner sobe, então a mesma imagem serve em qualquer ambiente.
|
|
167
|
-
|
|
168
|
-
```yaml
|
|
169
|
-
# compose.yaml
|
|
170
|
-
services:
|
|
171
|
-
loja: # host: http://localhost:8080
|
|
172
|
-
build: ./loja
|
|
173
|
-
ports: ["8080:80"]
|
|
174
|
-
environment:
|
|
175
|
-
VITRAL_REMOTES: '{"carrinho":"/mf/carrinho/vitral.json","busca":"/mf/busca/vitral.json"}'
|
|
176
|
-
carrinho: # remote React
|
|
177
|
-
build: ./carrinho
|
|
178
|
-
busca: # remote Vue
|
|
179
|
-
build: ./busca
|
|
180
|
-
```
|
|
181
|
-
|
|
182
|
-
O nginx do host repassa `/mf/carrinho/` para o contêiner `carrinho`. Tudo fica na mesma origem: sem CORS e com uma porta só. Parar o contêiner `carrinho` mostra o erro só no lugar do carrinho.
|
|
183
|
-
|
|
184
|
-
No Kubernetes, as mesmas imagens funcionam com um Service por remote; o Ingress pode fazer o papel do nginx do host. Se os remotes ficam num CDN, troque `VITRAL_REMOTES` pelas URLs do CDN.
|
|
185
|
-
|
|
186
|
-
Exemplo completo, com Dockerfiles e configuração do nginx: [`examples/docker`](https://github.com/joaogabriel15/vitral/tree/main/examples/docker).
|
|
187
|
-
|
|
188
130
|
## Frameworks
|
|
189
131
|
|
|
190
132
|
| Framework | Remote | Host | Import |
|
|
@@ -200,258 +142,251 @@ Exemplo completo, com Dockerfiles e configuração do nginx: [`examples/docker`]
|
|
|
200
142
|
| Lit e Web Components | `elementRemote('meu-widget')` | `<vitral-remote>` | `vitral/element` |
|
|
201
143
|
| JS e TypeScript puro | `component({ render })` | `<vitral-remote>` | `vitral` |
|
|
202
144
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
Uma zona do Multi-Zones vira remote sem reescrever o código Next (`vitral({ next: true })`), e o app Next principal vira host com `withVitral` e `<NextRemote>`, trocando de área sem recarregar. Veja [Next.js](https://joaogabriel15.github.io/vitral/frameworks/next).
|
|
145
|
+
Host e remote não precisam ser do mesmo framework. Cada um tem uma página com exemplo completo em [Frameworks](https://joaogabriel15.github.io/vitral/frameworks/react).
|
|
206
146
|
|
|
207
|
-
|
|
147
|
+
## Next.js e Nuxt como host
|
|
208
148
|
|
|
209
|
-
|
|
210
|
-
<script setup>
|
|
211
|
-
import { VitralRemote } from 'vitral/vue'
|
|
212
|
-
</script>
|
|
149
|
+
O remote é sempre um projeto Vite (React, Vue ou outro), como no Começo rápido acima. O host pode ser um app Next ou Nuxt.
|
|
213
150
|
|
|
214
|
-
|
|
215
|
-
<VitralRemote name="carrinho" :props="{ userId: 42 }">
|
|
216
|
-
<template #fallback>Carregando…</template>
|
|
217
|
-
<template #error="{ retry }"><button @click="retry">Tentar de novo</button></template>
|
|
218
|
-
</VitralRemote>
|
|
219
|
-
</template>
|
|
220
|
-
```
|
|
151
|
+
**Next.js (App Router):**
|
|
221
152
|
|
|
222
|
-
|
|
153
|
+
```tsx
|
|
154
|
+
// app/carrinho.tsx
|
|
155
|
+
'use client'
|
|
156
|
+
import { configure } from 'vitral'
|
|
157
|
+
import { Remote } from 'vitral/react'
|
|
223
158
|
|
|
224
|
-
|
|
159
|
+
if (typeof window !== 'undefined') {
|
|
160
|
+
configure({ remotes: { carrinho: 'https://cdn.empresa.com/carrinho/vitral.json' } })
|
|
161
|
+
}
|
|
225
162
|
|
|
226
|
-
|
|
227
|
-
<
|
|
228
|
-
|
|
229
|
-
|
|
163
|
+
export function Carrinho({ userId }: { userId: number }) {
|
|
164
|
+
return <Remote name="carrinho" props={{ userId }} fallback={<p>Carregando…</p>} />
|
|
165
|
+
}
|
|
166
|
+
```
|
|
230
167
|
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
168
|
+
```tsx
|
|
169
|
+
// app/page.tsx
|
|
170
|
+
import { Carrinho } from './carrinho'
|
|
234
171
|
|
|
235
|
-
|
|
236
|
-
<
|
|
237
|
-
|
|
238
|
-
</vitral-remote>
|
|
172
|
+
export default function Page() {
|
|
173
|
+
return <main><Carrinho userId={42} /></main>
|
|
174
|
+
}
|
|
239
175
|
```
|
|
240
176
|
|
|
241
|
-
|
|
177
|
+
**Nuxt 3 e 4:**
|
|
242
178
|
|
|
243
179
|
```ts
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
<p>Olá, ${nome}</p>
|
|
250
|
-
<button onclick=${() => state.cliques++}>cliques: ${state.cliques}</button>
|
|
251
|
-
`,
|
|
180
|
+
// app/plugins/vitral.client.ts
|
|
181
|
+
import { configure } from 'vitral'
|
|
182
|
+
|
|
183
|
+
export default defineNuxtPlugin(() => {
|
|
184
|
+
configure({ remotes: { catalogo: 'https://cdn.empresa.com/catalogo/vitral.json' } })
|
|
252
185
|
})
|
|
253
186
|
```
|
|
254
187
|
|
|
255
|
-
|
|
188
|
+
```vue
|
|
189
|
+
<!-- app/pages/index.vue -->
|
|
190
|
+
<script setup lang="ts">
|
|
191
|
+
import { VitralRemote } from 'vitral/vue'
|
|
192
|
+
</script>
|
|
256
193
|
|
|
257
|
-
|
|
194
|
+
<template>
|
|
195
|
+
<VitralRemote name="catalogo" :props="{ userId: 42 }">
|
|
196
|
+
<template #fallback><p>Carregando…</p></template>
|
|
197
|
+
</VitralRemote>
|
|
198
|
+
</template>
|
|
199
|
+
```
|
|
258
200
|
|
|
259
|
-
|
|
260
|
-
- **Overrides:** `http://localhost:3000/?vitral=carrinho@http://localhost:5174` troca a URL de um remote sem mexer no host. Só vale em `localhost` ou com `configure({ devOverrides: true })`. Para guardar no navegador, use `devtools()` de `vitral/devtools`.
|
|
261
|
-
- **Tipos das props:** o build publica `vitral.d.ts`. No host, `npx vitral types` gera `vitral-env.d.ts`, e uma prop errada passa a não compilar.
|
|
201
|
+
Nos dois, o servidor renderiza o `fallback` e o remote monta no navegador. Não precisa de `dynamic(..., { ssr: false })` nem de `<ClientOnly>`.
|
|
262
202
|
|
|
263
|
-
##
|
|
203
|
+
## Multi-Zones ou vitral
|
|
264
204
|
|
|
265
|
-
|
|
266
|
-
import { events } from 'vitral'
|
|
205
|
+
Exemplo: uma loja em Next.js com a área "Minha conta", feita por outra equipe.
|
|
267
206
|
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
207
|
+
<p align="center">
|
|
208
|
+
<picture>
|
|
209
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/joaogabriel15/vitral/main/docs/public/marca/multizonas-escuro.png">
|
|
210
|
+
<img src="https://raw.githubusercontent.com/joaogabriel15/vitral/main/docs/public/marca/multizonas.png" width="900" alt="À esquerda, Multi-Zones: dois apps Next, rewrites e a página recarrega ao trocar de área (0,8 s). À direita, vitral: um app Next com withVitral, a conta é um remote dentro do layout e a troca é sem recarregar (0,2 s).">
|
|
211
|
+
</picture>
|
|
212
|
+
</p>
|
|
274
213
|
|
|
275
|
-
|
|
214
|
+
### Hoje, com Multi-Zones
|
|
276
215
|
|
|
277
|
-
|
|
278
|
-
import { provide, shared } from 'vitral'
|
|
216
|
+
São dois apps Next. A loja repassa as URLs de `/conta` para o app da conta.
|
|
279
217
|
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
const nome = useShared('usuario', (u) => u?.nome) // React, Preact, Vue e Solid
|
|
218
|
+
```
|
|
219
|
+
loja/ app Next principal
|
|
220
|
+
conta/ segundo app Next (a zona)
|
|
284
221
|
```
|
|
285
222
|
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
223
|
+
```js
|
|
224
|
+
// conta/next.config.js
|
|
225
|
+
module.exports = {
|
|
226
|
+
basePath: '/conta',
|
|
227
|
+
assetPrefix: '/conta-static',
|
|
228
|
+
}
|
|
229
|
+
```
|
|
291
230
|
|
|
292
|
-
|
|
231
|
+
```tsx
|
|
232
|
+
// conta/pages/index.tsx
|
|
233
|
+
export default function Conta() {
|
|
234
|
+
return <h1>Minha conta</h1>
|
|
235
|
+
}
|
|
236
|
+
```
|
|
293
237
|
|
|
294
|
-
|
|
238
|
+
```js
|
|
239
|
+
// loja/next.config.js
|
|
240
|
+
module.exports = {
|
|
241
|
+
async rewrites() {
|
|
242
|
+
return [
|
|
243
|
+
{ source: '/conta', destination: `${process.env.CONTA_URL}/conta` },
|
|
244
|
+
{ source: '/conta/:path+', destination: `${process.env.CONTA_URL}/conta/:path+` },
|
|
245
|
+
{ source: '/conta-static/:path+', destination: `${process.env.CONTA_URL}/conta-static/:path+` },
|
|
246
|
+
]
|
|
247
|
+
},
|
|
248
|
+
}
|
|
249
|
+
```
|
|
295
250
|
|
|
296
|
-
```
|
|
297
|
-
|
|
251
|
+
```tsx
|
|
252
|
+
// loja/components/Menu.tsx
|
|
253
|
+
// <a>, não <Link>: a página recarrega e baixa Next e React de novo.
|
|
254
|
+
<a href="/conta">Minha conta</a>
|
|
298
255
|
```
|
|
299
256
|
|
|
300
|
-
|
|
257
|
+
### O mesmo app com vitral
|
|
301
258
|
|
|
302
|
-
|
|
259
|
+
A loja continua sendo o único app Next. A conta vira um remote: um projeto Vite com o mesmo componente.
|
|
303
260
|
|
|
304
|
-
```js
|
|
305
|
-
vitral({ theme: 'host' }) // var(--x) usa o valor do host, se existir
|
|
306
|
-
configure({ styles: { inherit: ['/assets/base.css'] } }) // CSS base do host dentro do Shadow DOM
|
|
307
261
|
```
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
## Configuração
|
|
262
|
+
loja/ app Next (o host)
|
|
263
|
+
conta/ projeto Vite (o remote)
|
|
264
|
+
```
|
|
312
265
|
|
|
313
266
|
```js
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
isolate: 'none', // ou 'shadow'
|
|
320
|
-
})
|
|
267
|
+
// conta/vite.config.js (no lugar do next.config.js da zona)
|
|
268
|
+
import react from '@vitejs/plugin-react'
|
|
269
|
+
import vitral from 'vitral/vite'
|
|
270
|
+
|
|
271
|
+
export default { plugins: [react(), vitral({ name: 'conta', dedupe: ['react'] })] }
|
|
321
272
|
```
|
|
322
273
|
|
|
323
|
-
|
|
274
|
+
```tsx
|
|
275
|
+
// conta/src/App.tsx (o mesmo componente da página)
|
|
276
|
+
export default function Conta() {
|
|
277
|
+
return <h1>Minha conta</h1>
|
|
278
|
+
}
|
|
279
|
+
```
|
|
324
280
|
|
|
325
281
|
```js
|
|
326
|
-
|
|
282
|
+
// loja/next.config.js (no lugar das rewrites)
|
|
283
|
+
const { withVitral } = require('vitral/next-config')
|
|
284
|
+
|
|
285
|
+
module.exports = withVitral({}, {
|
|
327
286
|
remotes: {
|
|
328
|
-
|
|
329
|
-
menu: { module: () => import('./menu') }, // remote local, sem rede
|
|
287
|
+
conta: { url: 'https://cdn.empresa.com/conta/vitral.json', basePath: '/conta' },
|
|
330
288
|
},
|
|
331
289
|
})
|
|
332
290
|
```
|
|
333
291
|
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
| `code` | Quando |
|
|
339
|
-
|---|---|
|
|
340
|
-
| `NOT_REGISTERED` | Nome não registrado em `configure` |
|
|
341
|
-
| `ORIGIN_BLOCKED` | URL fora de `allowedOrigins` |
|
|
342
|
-
| `TIMEOUT` | Não respondeu dentro de `timeout` |
|
|
343
|
-
| `INTEGRITY` | O hash do JS não confere |
|
|
344
|
-
| `INVALID_MODULE` | O arquivo não exporta `mount()` |
|
|
345
|
-
| `LOAD_FAILED` | Erro de rede ou HTTP |
|
|
346
|
-
| `MOUNT_FAILED` | O remote lançou erro ao montar |
|
|
347
|
-
| `RENDER_FAILED` | O remote quebrou depois de montado |
|
|
348
|
-
|
|
349
|
-
## Performance
|
|
350
|
-
|
|
351
|
-
Remote com `import()` também gera `dist/split/`: o navegador baixa só o que o remote usa ao abrir, e o resto chega no `import()`, conferido pelo mesmo hash. Hosts antigos continuam usando o arquivo único.
|
|
292
|
+
```tsx
|
|
293
|
+
// loja/pages/_app.tsx (só acrescenta <VitralNext />)
|
|
294
|
+
import { VitralNext } from 'vitral/next-host'
|
|
352
295
|
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
Assim que o manifesto chega, o JS e o CSS do remote baixam juntos. A montagem
|
|
357
|
-
espera os dois, para o remote não aparecer sem estilo. `configure()` abre a
|
|
358
|
-
conexão com a origem de cada remote (`<link rel="preconnect">`).
|
|
359
|
-
|
|
360
|
-
```js
|
|
361
|
-
import { preload } from 'vitral'
|
|
362
|
-
// Baixa JS e CSS sem montar, por exemplo no hover de um link
|
|
363
|
-
link.addEventListener('pointerenter', () => preload('checkout'), { once: true })
|
|
296
|
+
export default function App({ Component, pageProps }) {
|
|
297
|
+
return <><VitralNext /><Component {...pageProps} /></>
|
|
298
|
+
}
|
|
364
299
|
```
|
|
365
300
|
|
|
366
|
-
|
|
301
|
+
```tsx
|
|
302
|
+
// loja/pages/conta/[[...slug]].tsx (arquivo novo: a página que mostra a conta)
|
|
303
|
+
import { NextRemote } from 'vitral/next-host'
|
|
367
304
|
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
<!-- monta com o navegador ocioso, mas já baixa no hover -->
|
|
372
|
-
<vitral-remote name="checkout" loading="idle" prefetch="hover"></vitral-remote>
|
|
373
|
-
<!-- remote que aparece logo ao abrir a página -->
|
|
374
|
-
<vitral-remote name="cabecalho" priority="high"></vitral-remote>
|
|
305
|
+
export default function Conta() {
|
|
306
|
+
return <Layout><NextRemote name="conta" fallback={<p>Carregando…</p>} /></Layout>
|
|
307
|
+
}
|
|
375
308
|
```
|
|
376
309
|
|
|
377
|
-
```
|
|
378
|
-
|
|
310
|
+
```tsx
|
|
311
|
+
// loja/components/Menu.tsx
|
|
312
|
+
// <Link> normal: a troca é sem recarregar, e o React não baixa de novo.
|
|
313
|
+
<Link href="/conta">Minha conta</Link>
|
|
379
314
|
```
|
|
380
315
|
|
|
381
|
-
|
|
382
|
-
| --- | --- | --- |
|
|
383
|
-
| `loading` | `lazy`, `idle` | Monta a 200px de aparecer na tela, ou com o navegador ocioso |
|
|
384
|
-
| `prefetch` | `hover`, `visible`, `idle` | Chama `preload()` antes de montar |
|
|
385
|
-
| `priority` | `high` | `fetchpriority` alto no manifesto, no JS e no CSS |
|
|
386
|
-
| `keepAlive` (`keep-alive`) | `true` ou o máximo | Ao sair da página, o remote vai para um contêiner oculto (LRU, padrão 5); na volta só recebe as props novas |
|
|
316
|
+
Se o código da conta já usa `next/link` ou `useRouter`, não precisa reescrever: `vitral({ name: 'conta', next: { basePath: '/conta' } })` builda esse código com o Vite.
|
|
387
317
|
|
|
388
|
-
|
|
318
|
+
### O que muda
|
|
389
319
|
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
320
|
+
| | Multi-Zones | vitral |
|
|
321
|
+
|---|---|---|
|
|
322
|
+
| Apps Next | Um por área | Só a loja |
|
|
323
|
+
| Configuração | `basePath` e `assetPrefix` na zona, `rewrites` na loja | `withVitral` na loja, plugin na conta |
|
|
324
|
+
| Trocar de área | Recarrega a página (0,8 s no benchmark) | Sem recarregar (0,2 s) |
|
|
325
|
+
| React e Next | Baixados de novo em cada área | Uma cópia para a página toda |
|
|
326
|
+
| Layout da loja | Cada zona repete o seu | A conta fica dentro do layout da loja |
|
|
396
327
|
|
|
397
|
-
|
|
328
|
+
Guia completo, com SSR por rota e prefetch: [Migrar do Next.js Multi-Zones](https://joaogabriel15.github.io/vitral/migracao/multi-zones).
|
|
398
329
|
|
|
399
|
-
|
|
400
|
-
`vitral:<remote>:<etapa>`. As etapas são `manifest`, `js`, `css` e `mount`.
|
|
401
|
-
Elas aparecem na aba Performance do DevTools. Para mandar ao seu RUM:
|
|
330
|
+
## O que mais vem junto
|
|
402
331
|
|
|
403
|
-
|
|
404
|
-
configure({
|
|
405
|
-
onMetric: ({ name, stage, duration }) => rum.send(`vitral.${stage}`, duration, { remote: name }),
|
|
406
|
-
})
|
|
407
|
-
```
|
|
408
|
-
|
|
409
|
-
O evento `vitral-ready` (e o `ready` do componente Vue) traz os tempos em
|
|
410
|
-
`detail.timings`, por exemplo `{ manifest: 12.3, js: 40.1, css: 8, mount: 2.4 }`.
|
|
411
|
-
Um remote local (`module`) só mede `css` e `mount`. Erros dentro do
|
|
412
|
-
`onMetric` são ignorados.
|
|
332
|
+
**Dependências compartilhadas.** Com `vitral({ dedupe: ['react'] })`, o remote usa o React que já está na página e não baixa outra cópia. [Dedupe](https://joaogabriel15.github.io/vitral/aprender/dedupe)
|
|
413
333
|
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
334
|
+
<p align="center">
|
|
335
|
+
<picture>
|
|
336
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/joaogabriel15/vitral/main/docs/public/marca/dedupe-escuro.png">
|
|
337
|
+
<img src="https://raw.githubusercontent.com/joaogabriel15/vitral/main/docs/public/marca/dedupe.png" width="900" alt="Sem dedupe, cada remote baixa o próprio React. Com dedupe, os remotes usam o React que já está na página quando a versão serve; o que não serve baixa o próprio.">
|
|
338
|
+
</picture>
|
|
339
|
+
</p>
|
|
417
340
|
|
|
418
|
-
|
|
419
|
-
vitral({ dedupe: ['react'] })
|
|
420
|
-
```
|
|
341
|
+
**Comunicação entre remotes.** `events` manda mensagens entre remotes, e `provide` e `shared` guardam estado comum, como o usuário logado. [Props e eventos](https://joaogabriel15.github.io/vitral/aprender/props-eventos) e [Contexto compartilhado](https://joaogabriel15.github.io/vitral/aprender/contexto)
|
|
421
342
|
|
|
422
|
-
|
|
343
|
+
<p align="center">
|
|
344
|
+
<picture>
|
|
345
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/joaogabriel15/vitral/main/docs/public/marca/comunicacao-escuro.png">
|
|
346
|
+
<img src="https://raw.githubusercontent.com/joaogabriel15/vitral/main/docs/public/marca/comunicacao.png" width="900" alt="Três remotes em React, Vue e Angular. O carrinho emite um evento, a busca recebe pelo mesmo barramento, e a conta lê o usuário que o host criou com provide.">
|
|
347
|
+
</picture>
|
|
348
|
+
</p>
|
|
423
349
|
|
|
424
|
-
|
|
350
|
+
**Segurança.** O JS só roda se vier de uma origem permitida e, com `integrity`, se o hash bater. [SRI e origens](https://joaogabriel15.github.io/vitral/aprender/seguranca)
|
|
425
351
|
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
352
|
+
<p align="center">
|
|
353
|
+
<picture>
|
|
354
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/joaogabriel15/vitral/main/docs/public/marca/seguranca-escuro.png">
|
|
355
|
+
<img src="https://raw.githubusercontent.com/joaogabriel15/vitral/main/docs/public/marca/seguranca.png" width="900" alt="O host configura allowedOrigins e integrity. Antes de rodar, a lib confere a origem e o SHA-384. Se um dos dois falha, nada executa e o erro aparece no lugar do remote.">
|
|
356
|
+
</picture>
|
|
357
|
+
</p>
|
|
431
358
|
|
|
432
|
-
|
|
359
|
+
E também:
|
|
433
360
|
|
|
434
|
-
-
|
|
435
|
-
-
|
|
436
|
-
-
|
|
437
|
-
-
|
|
438
|
-
-
|
|
439
|
-
-
|
|
361
|
+
- **CSS e Tailwind:** o CSS de cada remote vale só dentro dele, ou use Shadow DOM com `isolate="shadow"`. [Estilos](https://joaogabriel15.github.io/vitral/aprender/estilos)
|
|
362
|
+
- **Carregamento:** `loading="lazy"`, `prefetch="hover"` e `keepAlive` para abrir e voltar mais rápido. [Carregamento](https://joaogabriel15.github.io/vitral/aprender/carregamento)
|
|
363
|
+
- **Erros:** cada erro tem um código e uma página com causa e correção, e `retry` monta só aquele remote de novo. [Erros](https://joaogabriel15.github.io/vitral/erros/)
|
|
364
|
+
- **Props tipadas:** `npx vitral types` faz uma prop errada não compilar no host. [Contratos](https://joaogabriel15.github.io/vitral/aprender/contratos)
|
|
365
|
+
- **Rotas, SSR e deploy:** app shell por rota, HTML do remote no servidor, canary e rollback. [Rotas](https://joaogabriel15.github.io/vitral/aprender/rotas), [SSR](https://joaogabriel15.github.io/vitral/aprender/ssr) e [Canary](https://joaogabriel15.github.io/vitral/aprender/canary)
|
|
366
|
+
- **Testes:** `mockRemote` e `failingRemote` testam o host sem rede. [Testes](https://joaogabriel15.github.io/vitral/aprender/testes)
|
|
440
367
|
|
|
441
|
-
##
|
|
368
|
+
## Rodar local e com Docker
|
|
442
369
|
|
|
443
|
-
|
|
444
|
-
import { mockRemote, failingRemote } from 'vitral/testing'
|
|
370
|
+
Cada remote roda no próprio `vite dev`, numa porta, e o host aponta para essas portas:
|
|
445
371
|
|
|
446
|
-
|
|
447
|
-
//
|
|
448
|
-
|
|
372
|
+
```json
|
|
373
|
+
// loja/public/remotes.json
|
|
374
|
+
{
|
|
375
|
+
"carrinho": "http://localhost:5174/vitral.json",
|
|
376
|
+
"busca": "http://localhost:5175/vitral.json"
|
|
377
|
+
}
|
|
378
|
+
```
|
|
449
379
|
|
|
450
|
-
|
|
380
|
+
```js
|
|
381
|
+
// loja/src/main.jsx
|
|
382
|
+
configure({ remotes: '/remotes.json' })
|
|
451
383
|
```
|
|
452
384
|
|
|
385
|
+
Editar o remote atualiza o host sem recarregar a página. Com Docker, cada remote vira uma imagem nginx e o host lê a lista de remotes de uma variável de ambiente, então a mesma imagem serve em qualquer ambiente. [Local e Docker](https://joaogabriel15.github.io/vitral/aprender/local-e-docker) e o exemplo [`examples/docker`](https://github.com/joaogabriel15/vitral/tree/main/examples/docker).
|
|
386
|
+
|
|
453
387
|
## Links
|
|
454
388
|
|
|
389
|
+
- [Documentação](https://joaogabriel15.github.io/vitral/): guias, referência e páginas de erro.
|
|
455
390
|
- [Exemplos](https://github.com/joaogabriel15/vitral/tree/main/examples): o mesmo remote em 8 frameworks e 9 hosts.
|
|
456
391
|
- [Como contribuir](https://github.com/joaogabriel15/vitral/blob/main/CONTRIBUTING.md)
|
|
457
392
|
- Licença [MIT](https://github.com/joaogabriel15/vitral/blob/main/LICENSE). Feito por [Pacheco Codes](https://pacheco.dev.br/).
|
package/dist/next-server.d.ts
CHANGED
|
@@ -18,7 +18,7 @@ interface RemotePropsOptions {
|
|
|
18
18
|
*/
|
|
19
19
|
staleWhileRevalidate?: number;
|
|
20
20
|
/**
|
|
21
|
-
* Origem para o `url` relativo do remote (`/
|
|
21
|
+
* Origem para o `url` relativo do remote (`/conta/vitral.json`).
|
|
22
22
|
* Padrão: `VITRAL_ORIGIN` do ambiente, ou o próprio servidor Next em
|
|
23
23
|
* `http://127.0.0.1:$PORT`. O header `Host` da requisição nunca é usado: um
|
|
24
24
|
* cliente poderia apontar o servidor para outra máquina.
|
package/dist/sw.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ import './errors-kjBv6IH_.js';
|
|
|
8
8
|
* // sw.js do host
|
|
9
9
|
* import { remoteFiles } from 'vitral/sw'
|
|
10
10
|
* self.addEventListener('install', (e) => e.waitUntil(
|
|
11
|
-
* remoteFiles('/
|
|
11
|
+
* remoteFiles('/conta/vitral.json').then((urls) => caches.open('remotes').then((c) => c.addAll(urls))),
|
|
12
12
|
* ))
|
|
13
13
|
*/
|
|
14
14
|
|
|
@@ -48,7 +48,7 @@ interface Scope {
|
|
|
48
48
|
*
|
|
49
49
|
* // sw.js do host
|
|
50
50
|
* import { remoteWorker } from 'vitral/sw'
|
|
51
|
-
* remoteWorker(self, { manifests: ['/
|
|
51
|
+
* remoteWorker(self, { manifests: ['/conta/vitral.json'] })
|
|
52
52
|
*/
|
|
53
53
|
declare function remoteWorker(self: Scope, o: RemoteWorkerOptions): void;
|
|
54
54
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vitral",
|
|
3
|
-
"version": "0.11.
|
|
4
|
-
"description": "Micro-frontends
|
|
3
|
+
"version": "0.11.3",
|
|
4
|
+
"description": "Micro-frontends com qualquer framework, sem configurar build no host. React, Next.js, Vue, Nuxt, Angular, Svelte e outros na mesma página.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"micro-frontend",
|
|
7
7
|
"micro-frontends",
|
|
@@ -27,7 +27,11 @@
|
|
|
27
27
|
"astro",
|
|
28
28
|
"lit",
|
|
29
29
|
"web-components",
|
|
30
|
-
"typescript"
|
|
30
|
+
"typescript",
|
|
31
|
+
"micro-frontend-framework",
|
|
32
|
+
"module-federation-alternative",
|
|
33
|
+
"nextjs-multi-zones",
|
|
34
|
+
"multi-zones"
|
|
31
35
|
],
|
|
32
36
|
"homepage": "https://joaogabriel15.github.io/vitral/",
|
|
33
37
|
"bugs": {
|