Skip to content

Commit

Permalink
Translate the new SSR folder
Browse files Browse the repository at this point in the history
  • Loading branch information
GuiDevloper committed Mar 4, 2022
1 parent c027cbc commit 161ed2f
Show file tree
Hide file tree
Showing 8 changed files with 151 additions and 151 deletions.
58 changes: 29 additions & 29 deletions src/guide/ssr/build-config.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
# Build Configuration
# Configuração da Compilação

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).
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).

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

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.
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.

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).
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`).

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.
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.

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`:
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:

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

## Example Configuration
## Exemplo de Configuração

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.
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.

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

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

if (!process.env.SSR) {
// Point entry to your app's client entry file
// Aponta a entrada para o arquivo de entrada do cliente do seu aplicativo
webpackConfig
.entry('app')
.clear()
.add('./src/entry-client.js')
return
}

// Point entry to your app's server entry file
// Aponta a entrada para o arquivo de entrada do servidor do seu aplicativo
webpackConfig
.entry('app')
.clear()
.add('./src/entry-server.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.
// Permite que o webpack lide com importações dinâmicas ao estilo Node
// e também diz ao `vue-loader` para emitir código orientado ao servidor ao
// compilar componentes Vue.
webpackConfig.target('node')
// This tells the server bundle to use Node-style exports
// Isso diz ao pacote do servidor para usar exportações no estilo Node
webpackConfig.output.libraryTarget('commonjs2')

webpackConfig
Expand All @@ -66,11 +66,11 @@ module.exports = {

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

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

webpackConfig.optimization.splitChunks(false).minimize(false)
Expand All @@ -89,18 +89,18 @@ module.exports = {
}
```

## Externals Caveats
## Limitações do _Externals_

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.
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.

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.
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.

## Generating `clientManifest`
## Gerando `clientManifest`

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.
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.

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

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

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).
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_).
40 changes: 20 additions & 20 deletions src/guide/ssr/getting-started.md
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
# Getting Started
# Começando

> This guide is currently under active development
> Este guia atualmente está sob ativo desenvolvimento
## Installation
## Instalação

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

```bash
npm install @vue/server-renderer
## OR
## OU
yarn add @vue/server-renderer
```

#### Notes
#### Notas

- It's recommended to use Node.js version 12+.
- `@vue/server-renderer` and `vue` must have matching versions.
- `@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.
- Recomenda-se usar o Node.js em versão 12+.
- `@vue/server-renderer` e `vue` devem ter versões correspondentes.
- `@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.

## Rendering a Vue Application
## Renderizando um Aplicativo Vue

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

```js
const { createSSRApp } = require('vue')
Expand All @@ -31,11 +31,11 @@ const app = createSSRApp({
user: 'John Doe'
}
},
template: `<div>Current user is: {{ user }}</div>`
template: `<div>O usuário atual é: {{ user }}</div>`
})
```

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.
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.

```js{2,13}
const { createSSRApp } = require('vue')
Expand All @@ -47,19 +47,19 @@ const app = createSSRApp({
user: 'John Doe'
}
},
template: `<div>Current user is: {{ user }}</div>`
template: `<div>O usuário atual é: {{ user }}</div>`
})
const appContent = await renderToString(app)
```

## Integrating with a Server
## Integrando com um Servidor

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

```bash
npm install express
## OR
## OU
yarn add express
```

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

const appContent = await renderToString(app)
const html = `
<html>
<body>
<h1>My First Heading</h1>
<h1>Meu Primeiro Título</h1>
<div id="app">${appContent}</div>
</body>
</html>
Expand All @@ -96,4 +96,4 @@ server.get('*', async (req, res) => {
server.listen(8080)
```

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.
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).
24 changes: 12 additions & 12 deletions src/guide/ssr/hydration.md
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
# Client Side Hydration
# Hidratação _Client-Side_

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.
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_.

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

```js
app.mount('#app')
```

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.
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.

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.
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.

### Hydration Caveats
### Limitações da Hidratação

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.
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á.

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.
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.

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:
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:

```html
<table>
<tr>
<td>hi</td>
<td>oi</td>
</tr>
</table>
```

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.
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_.

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.
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.
Loading

0 comments on commit 161ed2f

Please sign in to comment.