Skip to content

Commit 9f83414

Browse files
committed
docs: translate guide/migration/global-api-treeshaking
ref: #94
1 parent f9159e1 commit 9f83414

File tree

1 file changed

+40
-39
lines changed

1 file changed

+40
-39
lines changed

src/guide/migration/global-api-treeshaking.md

Lines changed: 40 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,21 @@ badges:
33
- breaking
44
---
55

6-
# Global API Treeshaking <MigrationBadges :badges="$frontmatter.badges" />
6+
# API Global Treeshaking <MigrationBadges :badges="$frontmatter.badges" />
77

8-
## 2.x Syntax
8+
## Syntax 2.x
99

10-
If you’ve ever had to manually manipulate DOM in Vue, you might have come across this pattern:
10+
Se você já teve que manipular manualmente o DOM no Vue, pode ter encontrado este padrão:
1111

1212
```js
1313
import Vue from 'vue'
1414

1515
Vue.nextTick(() => {
16-
// something DOM-related
16+
// algo relacionado ao DOM
1717
})
1818
```
1919

20-
Or, if you’ve been unit-testing an application involving [async components](/guide/component-dynamic-async.html), chances are you’ve written something like this:
20+
Ou, se você fez testes unitários em seu aplicativo envolvendo [componentes assíncronos](/guide/component-dynamic-async.html), provavelmente você escreveu algo assim:
2121

2222
```js
2323
import { shallowMount } from '@vue/test-utils'
@@ -26,33 +26,33 @@ import { MyComponent } from './MyComponent.vue'
2626
test('an async feature', async () => {
2727
const wrapper = shallowMount(MyComponent)
2828

29-
// execute some DOM-related tasks
29+
// execute alguma tarefa relacionada ao DOM
3030

3131
await wrapper.vm.$nextTick()
3232

33-
// run your assertions
33+
// execute seus assertions
3434
})
3535
```
3636

37-
`Vue.nextTick()` is a global API exposed directly on a single Vue object – in fact, the instance method `$nextTick()` is just a handy wrapper around `Vue.nextTick()` with the callback’s `this` context automatically bound to the current instance for convenience.
37+
`Vue.nextTick()` é uma API global exposta diretamente em um único objeto Vue - na verdade, o método de instância `$nextTick()` é apenas um *wrapper* em torno de `Vue.nextTick()` com o contexto `this` do retorno de chamada automaticamente vinculado à instância atual por conveniência.
3838

39-
But what if you’ve never had to deal with manual DOM manipulation, nor are you using or testing async components in our app? Or, what if, for whatever reason, you prefer to use the good old `window.setTimeout()` instead? In such a case, the code for `nextTick()` will become dead code – that is, code that’s written but never used. And dead code is hardly a good thing, especially in our client-side context where every kilobyte matters.
39+
Mas e se você nunca teve que lidar com a manipulação manual do DOM, nem está usando ou testando componentes assíncronos em nosso aplicativo? Ou, e se, por qualquer motivo, você preferir usar o bom e velho `window.setTimeout ()` em vez disso? Nesse caso, o código para `nextTick()` se tornará um código morto - ou seja, o código que foi escrito, mas nunca usado. E o código morto dificilmente é uma coisa boa, especialmente em nosso contexto do lado do cliente, onde cada kilobyte é importante.
4040

41-
Module bundlers like [webpack](https://webpack.js.org/) support [tree-shaking](https://webpack.js.org/guides/tree-shaking/), which is a fancy term for “dead code elimination.” Unfortunately, due to how the code is written in previous Vue versions, global APIs like `Vue.nextTick()` are not tree-shakeable and will be included in the final bundle regardless of where they are actually used or not.
41+
Os empacotadores de módulo, como o [webpack](https://webpack.js.org/), oferecem suporte à [tree-shaking](https://webpack.js.org/guides/tree-shaking/), que é um termo sofisticado para “eliminação de código morto”. Infelizmente, devido à forma como o código é escrito nas versões anteriores do Vue, APIs globais como `Vue.nextTick()` não podem ser *tree-shakeable* e serão incluídas no pacote final, independentemente de onde sejam realmente usadas ou não.
4242

43-
## 3.x Syntax
43+
## Syntax 3.x
4444

45-
In Vue 3, the global and internal APIs have been restructured with tree-shaking support in mind. As a result, the global APIs can now only be accessed as named exports for the ES Modules build. For example, our previous snippets should now look like this:
45+
No Vue 3, as APIs globais e internas foram reestruturadas tendo em mente o suporte para *tree-shakeable*. Como resultado, as APIs globais agora podem ser acessadas apenas como exportações nomeadas para a construção de Módulos ES. Por exemplo, nossos blocos de códigos anteriores agora devem ser semelhantes a este:
4646

4747
```js
4848
import { nextTick } from 'vue'
4949

5050
nextTick(() => {
51-
// something DOM-related
51+
// algo relacionado ao DOM
5252
})
5353
```
5454

55-
and
55+
e
5656

5757
```js
5858
import { shallowMount } from '@vue/test-utils'
@@ -62,60 +62,61 @@ import { nextTick } from 'vue'
6262
test('an async feature', async () => {
6363
const wrapper = shallowMount(MyComponent)
6464

65-
// execute some DOM-related tasks
65+
// execute alguma tarefa relacionada ao DOM
6666

6767
await nextTick()
6868

69-
// run your assertions
69+
// execute seus assertions
7070
})
7171
```
7272

73-
Calling `Vue.nextTick()` directly will now result in the infamous `undefined is not a function` error.
73+
Chamar `Vue.nextTick ()` diretamente agora resultará no abominável erro `undefined is not a function`.
7474

75-
With this change, provided the module bundler supports tree-shaking, global APIs that are not used in a Vue application will be eliminated from the final bundle, resulting in an optimal file size.
75+
Com essa mudança, com o bundler módulo suportando *tree-shaking*, APIs globais que não são usadas em seu aplicativo Vue serão eliminadas do pacote final, resultando em um tamanho ideal de arquivo.
7676

77-
## Affected APIs
77+
## APIs afetadas
7878

79-
These global APIs in Vue 2.x are affected by this change:
79+
Essas APIs globais no Vue 2.x são afetadas por esta mudança:
8080

8181
- `Vue.nextTick`
82-
- `Vue.observable` (replaced by `Vue.reactive`)
82+
- `Vue.observable` (substituído por `Vue.reactive`)
8383
- `Vue.version`
84-
- `Vue.compile` (only in full builds)
85-
- `Vue.set` (only in compat builds)
86-
- `Vue.delete` (only in compat builds)
84+
- `Vue.compile` (apenas em compilações completas)
85+
- `Vue.set` (apenas em construções compactas)
86+
- `Vue.delete` (apenas em construções compactas)
8787

88-
## Internal Helpers
88+
## Ajudantes Internos
8989

90-
In addition to public APIs, many of the internal components/helpers are now exported as named exports as well. This allows the compiler to output code that only imports features when they are used. For example the following template:
90+
Além das APIs públicas, muitos dos *components/helpers* internos agora também são exportados como exportações nomeadas. Isso permite que o compilador produza um código que importa apenas recursos quando eles são usados. Por exemplo, o seguinte template:
9191

9292
```html
9393
<transition>
94-
<div v-show="ok">hello</div>
94+
<div v-show="ok">olá</div>
9595
</transition>
9696
```
9797

98-
is compiled into something similar to the following:
98+
é compilado em algo semelhante ao seguinte:
9999

100100
```js
101101
import { h, Transition, withDirectives, vShow } from 'vue'
102102

103103
export function render() {
104-
return h(Transition, [withDirectives(h('div', 'hello'), [[vShow, this.ok]])])
104+
return h(Transition, [withDirectives(h('div', 'olá'), [[vShow, this.ok]])])
105105
}
106106
```
107107

108-
This essentially means the `Transition` component only gets imported when the application actually makes use of it. In other words, if the application doesn’t have any `<transition>` component, the code supporting this feature will not be present in the final bundle.
108+
Isso significa essencialmente que o componente `Transition` só é importado quando o aplicativo realmente faz uso dele.
109+
Em outras palavras, se o aplicativo não tiver nenhum componente `<transition>`, o código que suporta esse recurso não estará presente no pacote final.
109110

110-
With global tree-shaking, the user only “pay” for the features they actually use. Even better, knowing that optional features won't increase the bundle size for applications not using them, framework size has become much less a concern for additional core features in the future, if at all.
111+
Com o *tree-shake* global, o usuário apenas “paga” pelos recursos que realmente usa. Melhor ainda, sabendo que os recursos opcionais não aumentarão o tamanho do pacote para aplicativos que não os utilizam, o tamanho do framework se tornou muito menos uma preocupação para recursos centrais adicionais no futuro, se é que o fará.
111112

112-
::: warning Important
113-
The above only applies to the [ES Modules builds](/guide/installation.html#explanation-of-different-builds) for use with tree-shaking capable bundlers - the UMD build still includes all features and exposes everything on the Vue global variable (and the compiler will produce appropriate output to use APIs off the global instead of importing).
113+
::: aviso importante
114+
O que foi dito acima se aplica apenas as [Construções de Módulos ES](/guide/installation.html#explanation-of-different-builds) para uso com empacotadores capazes de aplicar *tree-shaking* - o construtor UMD ainda inclui todos os recursos e expõe tudo na variável global Vue (e o compilador produzirá a saída apropriada para usar APIs fora do global em vez de importar).
114115
:::
115116

116-
## Usage in Plugins
117+
## Uso em Plugins
117118

118-
If your plugin relies on an affected Vue 2.x global API, for instance:
119+
Se o seu plug-in depende de uma API global Vue 2.x afetada, por exemplo:
119120

120121
```js
121122
const plugin = {
@@ -127,7 +128,7 @@ const plugin = {
127128
}
128129
```
129130

130-
In Vue 3, you’ll have to import it explicitly:
131+
No Vue 3, você terá que importá-lo explicitamente:
131132

132133
```js
133134
import { nextTick } from 'vue'
@@ -141,7 +142,7 @@ const plugin = {
141142
}
142143
```
143144

144-
If you use a module bundle like webpack, this may cause Vue’s source code to be bundled into the plugin, and more often than not that’s not what you'd expect. A common practice to prevent this from happening is to configure the module bundler to exclude Vue from the final bundle. In webpack's case, you can use the [`externals`](https://webpack.js.org/configuration/externals/) configuration option:
145+
Se você usar um empacotador de módulo como webpack, isso pode fazer com que o código-fonte do Vue seja agrupado no plug-in e, na maioria das vezes, não é o que você esperava. Uma prática comum para evitar que isso aconteça é configurar o empacotador de módulo para excluir Vue do pacote final. No caso do webpack, você pode usar a opção de configuração [ʻexternals`] (https://webpack.js.org/configuration/externals/):
145146

146147
```js
147148
// webpack.config.js
@@ -153,9 +154,9 @@ module.exports = {
153154
}
154155
```
155156

156-
This will tell webpack to treat the Vue module as an external library and not bundle it.
157+
Isso dirá ao webpack para tratar o módulo Vue como uma biblioteca externa e não empacotá-lo.
157158

158-
If your module bundler of choice happens to be [Rollup](https://rollupjs.org/), you basically get the same effect for free, as by default Rollup will treat absolute module IDs (`'vue'` in our case) as external dependencies and not include them in the final bundle. During bundling though, it might emit a [“Treating vue as external dependency”](https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency) warning, which can be suppressed with the `external` option:
159+
Se o empacotador de módulo de sua escolha for [Rollup] (https://rollupjs.org/), você basicamente obterá o mesmo efeito de graça, pois por padrão o Rollup tratará IDs de módulo absolutos (`'vue'` em nosso caso ) como dependências externas e não incluí-las no pacote final. No entanto, durante o empacotamento, ele pode emitir um aviso [“Tratando vue como dependência externa”] (https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency), que pode ser suprimido com a opção `external`:
159160

160161
```js
161162
// rollup.config.js

0 commit comments

Comments
 (0)