Skip to content

Commit 161ed2f

Browse files
committed
Translate the new SSR folder
1 parent c027cbc commit 161ed2f

File tree

8 files changed

+151
-151
lines changed

8 files changed

+151
-151
lines changed

src/guide/ssr/build-config.md

+29-29
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
1-
# Build Configuration
1+
# Configuração da Compilação
22

3-
The webpack config for an SSR project will be similar to a client-only project. If you're not familiar with configuring webpack, you can find more information in the documentation for [Vue CLI](https://cli.vuejs.org/guide/webpack.html#working-with-webpack) or [configuring Vue Loader manually](https://vue-loader.vuejs.org/guide/#manual-setup).
3+
A configuração do webpack para um projeto SSR será semelhante a um projeto _client-only_. Se você não estiver familiarizado com a configuração do webpack, poderá encontrar mais informações na documentação do [Vue CLI](https://cli.vuejs.org/guide/webpack.html#working-with-webpack) ou [configurando o Vue Loader manualmente](https://vue-loader.vuejs.org/guide/#manual-setup).
44

5-
## Key Differences with Client-Only Builds
5+
## Principais Diferenças com Compilações _Client-Only_
66

7-
1. We need to create a [webpack manifest](https://webpack.js.org/concepts/manifest/) for our server-side code. This is a JSON file that webpack keeps to track how all the modules map to the output bundles.
7+
1. Precisamos criar um [_manifest_ do webpack](https://webpack.js.org/concepts/manifest/) para nosso código do lado do servidor. Este é um arquivo JSON que o webpack mantém para rastrear como todos os módulos são mapeados para os pacotes finais.
88

9-
2. We should [externalize application dependencies](https://webpack.js.org/configuration/externals/). This makes the server build much faster and generates a smaller bundle file. When doing this, we have to exclude dependencies that need to be processed by webpack (like `.css`. or `.vue` files).
9+
2. Devemos [externalizar dependências de aplicativos](https://webpack.js.org/configuration/externals/). Isso torna a compilação do servidor muito mais rápida e gera um arquivo de pacote menor. Ao fazer isso, temos que excluir dependências que precisam ser processadas pelo webpack (como arquivos `.css`. ou `.vue`).
1010

11-
3. We need to change webpack [target](https://webpack.js.org/concepts/targets/) to Node.js. This allows webpack to handle dynamic imports in a Node-appropriate fashion, and also tells `vue-loader` to emit server-oriented code when compiling Vue components.
11+
3. Precisamos alterar o [_target_](https://webpack.js.org/concepts/targets/) do webpack para Node.js. Isso permite que o webpack lide com importações dinâmicas de maneira apropriada ao Node, e também diz ao `vue-loader` para emitir código orientado ao servidor ao compilar componentes Vue.
1212

13-
4. When building a server entry, we would need to define an environment variable to indicate we are working with SSR. It might be helpful to add a few `scripts` to the project's `package.json`:
13+
4. Ao construir uma entrada de servidor, precisaríamos definir uma variável de ambiente para indicar que estamos trabalhando com SSR. Pode ser útil adicionar alguns `scripts` ao `package.json` do projeto:
1414

1515
```json
1616
"scripts": {
@@ -20,9 +20,9 @@ The webpack config for an SSR project will be similar to a client-only project.
2020
}
2121
```
2222

23-
## Example Configuration
23+
## Exemplo de Configuração
2424

25-
Below is a sample `vue.config.js` that adds SSR rendering to a Vue CLI project, but it can be adapted for any webpack build.
25+
Abaixo está um `vue.config.js` de exemplo que adiciona renderização SSR a um projeto Vue CLI, mas pode ser adaptado para qualquer compilação com webpack.
2626

2727
```js
2828
const { WebpackManifestPlugin } = require('webpack-manifest-plugin')
@@ -31,33 +31,33 @@ const webpack = require('webpack')
3131

3232
module.exports = {
3333
chainWebpack: webpackConfig => {
34-
// We need to disable cache loader, otherwise the client build
35-
// will used cached components from the server build
34+
// Precisamos desabilitar o cache loader, caso contrário a compilação do cliente
35+
// usará componentes em cache da compilação do servidor
3636
webpackConfig.module.rule('vue').uses.delete('cache-loader')
3737
webpackConfig.module.rule('js').uses.delete('cache-loader')
3838
webpackConfig.module.rule('ts').uses.delete('cache-loader')
3939
webpackConfig.module.rule('tsx').uses.delete('cache-loader')
4040

4141
if (!process.env.SSR) {
42-
// Point entry to your app's client entry file
42+
// Aponta a entrada para o arquivo de entrada do cliente do seu aplicativo
4343
webpackConfig
4444
.entry('app')
4545
.clear()
4646
.add('./src/entry-client.js')
4747
return
4848
}
4949

50-
// Point entry to your app's server entry file
50+
// Aponta a entrada para o arquivo de entrada do servidor do seu aplicativo
5151
webpackConfig
5252
.entry('app')
5353
.clear()
5454
.add('./src/entry-server.js')
5555

56-
// This allows webpack to handle dynamic imports in a Node-appropriate
57-
// fashion, and also tells `vue-loader` to emit server-oriented code when
58-
// compiling Vue components.
56+
// Permite que o webpack lide com importações dinâmicas ao estilo Node
57+
// e também diz ao `vue-loader` para emitir código orientado ao servidor ao
58+
// compilar componentes Vue.
5959
webpackConfig.target('node')
60-
// This tells the server bundle to use Node-style exports
60+
// Isso diz ao pacote do servidor para usar exportações no estilo Node
6161
webpackConfig.output.libraryTarget('commonjs2')
6262

6363
webpackConfig
@@ -66,11 +66,11 @@ module.exports = {
6666

6767
// https://webpack.js.org/configuration/externals/#function
6868
// https://github.com/liady/webpack-node-externals
69-
// Externalize app dependencies. This makes the server build much faster
70-
// and generates a smaller bundle file.
69+
// Externaliza dependências do app. Compila a parte do servidor mais rápido
70+
// e gera um arquivo de pacote menor.
7171

72-
// Do not externalize dependencies that need to be processed by webpack.
73-
// You should also whitelist deps that modify `global` (e.g. polyfills)
72+
// Não externalize dependências que precisam ser processadas pelo webpack.
73+
// Você deve permitir deps que modificam o `global` (ex.: polyfills)
7474
webpackConfig.externals(nodeExternals({ allowlist: /\.(css|vue)$/ }))
7575

7676
webpackConfig.optimization.splitChunks(false).minimize(false)
@@ -89,18 +89,18 @@ module.exports = {
8989
}
9090
```
9191

92-
## Externals Caveats
92+
## Limitações do _Externals_
9393

94-
Notice that in the `externals` option we are whitelisting CSS files. This is because CSS imported from dependencies should still be handled by webpack. If you are importing any other types of files that also rely on webpack (e.g. `*.vue`, `*.sass`), you should add them to the whitelist as well.
94+
Observe que na opção `externals` estamos permitindo arquivos CSS. Isso ocorre porque o CSS importado das dependências ainda deve ser tratado pelo webpack. Se estiver importando qualquer outro tipo de arquivo que também dependa do webpack (ex.: `*.vue`, `*.sass`), você deve adicioná-los à lista de permissões também.
9595

96-
If you are using `runInNewContext: 'once'` or `runInNewContext: true`, then you also need to whitelist polyfills that modify `global`, e.g. `babel-polyfill`. This is because when using the new context mode, **code inside a server bundle has its own `global` object.** Since you don't really need it on the server, it's actually easier to just import it in the client entry.
96+
Se estiver usando `runInNewContext: 'once'` ou `runInNewContext: true`, então você também precisa colocar _polyfills_ na lista de permissões que modificam `global`, ex.: `babel-polyfill`. Isso ocorre porque ao usar o novo modo de contexto, **o código dentro de um pacote de servidor tem seu próprio objeto `global`.** Como você realmente não precisa disso no servidor, é mais fácil importá-lo na entrada do cliente.
9797

98-
## Generating `clientManifest`
98+
## Gerando `clientManifest`
9999

100-
In addition to the server bundle, we can also generate a client build manifest. With the client manifest and the server bundle, the renderer now has information of both the server _and_ client builds. This way it can automatically infer and inject [preload / prefetch directives](https://css-tricks.com/prefetching-preloading-prebrowsing/), `<link>` and `<script>` tags into the rendered HTML.
100+
Além do pacote do servidor, também podemos gerar um manifesto da compilação do cliente. Com o manifesto do cliente e o pacote do servidor, o renderizador agora tem informações das compilações do servidor _e_ do cliente. Dessa forma, ele pode inferir e injetar automaticamente [diretivas de _preload / prefetch_](https://css-tricks.com/prefetching-preloading-prebrowsing/), tags `<link>` e `<script>` no HTML renderizado.
101101

102-
The benefits are two-fold:
102+
Os benefícios são duplos:
103103

104-
1. It can replace `html-webpack-plugin` for injecting the correct asset URLs when there are hashes in your generated filenames.
104+
1. Ele pode substituir o `html-webpack-plugin` para injetar os URLs de _assets_ corretos quando houver _hashes_ em seus nomes de arquivos gerados.
105105

106-
2. When rendering a bundle that leverages webpack's on-demand code splitting features, we can ensure the optimal chunks are preloaded / prefetched, and also intelligently inject `<script>` tags for needed async chunks to avoid waterfall requests on the client, thus improving TTI (time-to-interactive).
106+
2. Ao renderizar um pacote que aproveita os recursos de divisão de código sob demanda do webpack, podemos garantir que os fragmentos ideais sejam _preloaded / prefetched_ e também injetar de forma inteligente as tags `<script>` para os fragmentos assíncronos necessários e evitar solicitações em cascata no cliente, assim melhorando o TTI (_time-to-interactive_).

src/guide/ssr/getting-started.md

+20-20
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,26 @@
1-
# Getting Started
1+
# Começando
22

3-
> This guide is currently under active development
3+
> Este guia atualmente está sob ativo desenvolvimento
44
5-
## Installation
5+
## Instalação
66

7-
In order to create a server-side rendered application, we need to install the `@vue/server-renderer` package:
7+
Para criar um aplicativo renderizado no lado do servidor, precisamos instalar o pacote `@vue/server-renderer`:
88

99
```bash
1010
npm install @vue/server-renderer
11-
## OR
11+
## OU
1212
yarn add @vue/server-renderer
1313
```
1414

15-
#### Notes
15+
#### Notas
1616

17-
- It's recommended to use Node.js version 12+.
18-
- `@vue/server-renderer` and `vue` must have matching versions.
19-
- `@vue/server-renderer` relies on some Node.js native modules and therefore can only be used in Node.js. We may provide a simpler build that can be run in other JavaScript runtimes in the future.
17+
- Recomenda-se usar o Node.js em versão 12+.
18+
- `@vue/server-renderer` e `vue` devem ter versões correspondentes.
19+
- `@vue/server-renderer` depende de alguns módulos nativos do Node.js e, portanto, só pode ser usado no Node.js. Podemos fornecer uma versão mais simples que possa ser executada em outros _runtimes_ do JavaScript no futuro.
2020

21-
## Rendering a Vue Application
21+
## Renderizando um Aplicativo Vue
2222

23-
Unlike a client-only Vue application, which is created using `createApp`, an SSR application needs to be created using `createSSRApp`:
23+
Ao contrário de um aplicativo Vue _client-only_, que é criado usando `createApp`, um aplicativo SSR precisa ser criado usando `createSSRApp`:
2424

2525
```js
2626
const { createSSRApp } = require('vue')
@@ -31,11 +31,11 @@ const app = createSSRApp({
3131
user: 'John Doe'
3232
}
3333
},
34-
template: `<div>Current user is: {{ user }}</div>`
34+
template: `<div>O usuário atual é: {{ user }}</div>`
3535
})
3636
```
3737

38-
Now, we can use the `renderToString` function to render our application instance to a string. This function returns a Promise which resolves to the rendered HTML.
38+
Agora, podemos usar a função `renderToString` para renderizar nossa instância de aplicativo em uma string. Esta função retorna uma Promise que resolve para o HTML renderizado.
3939

4040
```js{2,13}
4141
const { createSSRApp } = require('vue')
@@ -47,19 +47,19 @@ const app = createSSRApp({
4747
user: 'John Doe'
4848
}
4949
},
50-
template: `<div>Current user is: {{ user }}</div>`
50+
template: `<div>O usuário atual é: {{ user }}</div>`
5151
})
5252
5353
const appContent = await renderToString(app)
5454
```
5555

56-
## Integrating with a Server
56+
## Integrando com um Servidor
5757

58-
To run an application, in this example we will use [Express](https://expressjs.com/):
58+
Para executar uma aplicação, neste exemplo usaremos [Express](https://expressjs.com/):
5959

6060
```bash
6161
npm install express
62-
## OR
62+
## OU
6363
yarn add express
6464
```
6565

@@ -77,14 +77,14 @@ server.get('*', async (req, res) => {
7777
user: 'John Doe'
7878
}
7979
},
80-
template: `<div>Current user is: {{ user }}</div>`
80+
template: `<div>O usuário atual é: {{ user }}</div>`
8181
})
8282

8383
const appContent = await renderToString(app)
8484
const html = `
8585
<html>
8686
<body>
87-
<h1>My First Heading</h1>
87+
<h1>Meu Primeiro Título</h1>
8888
<div id="app">${appContent}</div>
8989
</body>
9090
</html>
@@ -96,4 +96,4 @@ server.get('*', async (req, res) => {
9696
server.listen(8080)
9797
```
9898

99-
Now, when running this Node.js script, we can see a static HTML page on `localhost:8080`. However, this code is not _hydrated_: Vue hasn't yet taken over the static HTML sent by the server to turn it into dynamic DOM that can react to client-side data changes. This will be covered in the [Client Side Hydration](hydration.html) section.
99+
Agora, ao executar este script Node.js, podemos ver uma página HTML estática em `localhost:8080`. No entanto, este código não é _hidratado_: Vue ainda não assumiu o HTML estático enviado pelo servidor para transformá-lo em DOM dinâmico que pode reagir a alterações de dados _client-side_. Isso será abordado na seção [Hidratação _Client-Side_](hydration.html).

src/guide/ssr/hydration.md

+12-12
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
1-
# Client Side Hydration
1+
# Hidratação _Client-Side_
22

3-
Hydration refers to the client-side process during which Vue takes over the static HTML sent by the server and turns it into dynamic DOM that can react to client-side data changes.
3+
Hidratação refere-se ao processo _client-side_ durante o qual o Vue assume o HTML estático enviado pelo servidor e o transforma em DOM dinâmico que pode reagir às alterações de dados _client-side_.
44

5-
In `entry-client.js`, we are simply mounting the app with this line:
5+
Em `entry-client.js`, estamos simplesmente montando o aplicativo com esta linha:
66

77
```js
88
app.mount('#app')
99
```
1010

11-
Since the server has already rendered the markup, we obviously do not want to throw that away and re-create all the DOM elements. Instead, we want to "hydrate" the static markup and make it interactive.
11+
Como o servidor já renderizou a marcação, obviamente não queremos jogar isso fora e recriar todos os elementos DOM. Em vez disso, queremos "hidratar" a marcação estática e torná-la interativa.
1212

13-
Vue provides a `createSSRApp` method for use in client-side code (in this case, in our `entry-client.js`) to tell Vue to hydrate the existing static HTML instead of re-creating all the DOM elements.
13+
O Vue fornece um método `createSSRApp` para uso no código _client-side_ (neste caso, em nosso `entry-client.js`) para dizer ao Vue para hidratar o HTML estático existente em vez de recriar todos os elementos DOM.
1414

15-
### Hydration Caveats
15+
### Limitações da Hidratação
1616

17-
Vue will assert the client-side generated virtual DOM tree matches the DOM structure rendered from the server. If there is a mismatch, it will bail hydration, discard existing DOM and render from scratch. There will be a warning in the browser console but your site will still work.
17+
O Vue confirmará que a árvore DOM virtual gerada pelo cliente corresponde à estrutura DOM renderizada a partir do servidor. Se houver uma incompatibilidade, ele deixará a hidratação, descartará o DOM existente e renderizará do zero. Haverá um aviso no console do navegador, mas seu site ainda funcionará.
1818

19-
The first key way to ensure that SSR is working to ensuring your application state is the same on client and server. Take special care not to depend on APIs specific to the browser (like window width, device capability or localStorage) or server (such as Node built-ins), and take care where the same code will give different results when run in different places (such as when using timezones, timestamps, normalizing URLs or generating random numbers). See [Writing Universal Code](./universal.md) for more details.
19+
A primeira forma importante de garantir que o SSR esteja funcionando é garantir que o estado do aplicativo seja o mesmo no cliente e no servidor. Tome cuidado especial para não depender de APIs específicas do navegador (como largura da janela, capacidade do dispositivo ou localStorage) ou do servidor (como _built-ins_ do Node), e tome cuidado onde o mesmo código dará resultados diferentes quando executado em locais diferentes (como ao usar fusos horários, _timestamps_, normalizar URLs ou gerar números aleatórios). Consulte [Escrevendo Código Universal](./universal.md) para mais detalhes.
2020

21-
A second key thing to be aware of when using SSR + client hydration is that invalid HTML may be altered by the browser. For example, when you write this in a Vue template:
21+
Uma segunda coisa importante a ser observada ao usar o SSR + hidratação no cliente é que HTML inválido pode ser alterado pelo navegador. Por exemplo, quando você escreve isso em um _template_ Vue:
2222

2323
```html
2424
<table>
2525
<tr>
26-
<td>hi</td>
26+
<td>oi</td>
2727
</tr>
2828
</table>
2929
```
3030

31-
The browser will automatically inject `<tbody>` inside `<table>`, however, the virtual DOM generated by Vue does not contain `<tbody>`, so it will cause a mismatch. To ensure correct matching, make sure to write valid HTML in your templates.
31+
O navegador automaticamente injetará `<tbody>` dentro de `<table>`, entretanto, o DOM virtual gerado pelo Vue não contém `<tbody>`, então causará uma incompatibilidade. Para garantir a correspondência correta, certifique-se de escrever um HTML válido em seus _templates_.
3232

33-
You might consider using a HTML validator like [the W3C Markup Validation Service](https://validator.w3.org/) or [HTML-validate](https://html-validate.org/) to check your templates in development.
33+
Você pode usar um validador de HTML como [o W3C Markup Validation Service](https://validator.w3.org/) ou [HTML-validate](https://html-validate.org/) para verificar seus _templates_ em desenvolvimento.

0 commit comments

Comments
 (0)