|
1 | 1 |
|
2 |
| -# Polyfills and transpilers |
| 2 | +# Polyfills e transpilers |
3 | 3 |
|
4 |
| -The JavaScript language steadily evolves. New proposals to the language appear regularly, they are analyzed and, if considered worthy, are appended to the list at <https://tc39.github.io/ecma262/> and then progress to the [specification](https://www.ecma-international.org/publications-and-standards/standards/ecma-262/). |
| 4 | +A linguagem JavaScript evolui constantemente. Novas propostas para a linguagem aparecem regularmente, elas são analisadas e, se consideradas válidas, são anexadas à lista em <https://tc39.github.io/ecma262/> e depois progridem para a [especificação (en)](https://www.ecma-international.org/publications-and-standards/standards/ecma-262/). |
5 | 5 |
|
6 |
| -Teams behind JavaScript engines have their own ideas about what to implement first. They may decide to implement proposals that are in draft and postpone things that are already in the spec, because they are less interesting or just harder to do. |
| 6 | +Grupos por detrás dos interpretadores de JavaScript têm as suas próprias ideias sobre o que implementar primeiro. Eles podem decidir implementar propostas que estão em esboço e adiar coisas que já estão na spec, por serem menos interessantes ou apenas mais difíceis de fazer. |
7 | 7 |
|
8 |
| -So it's quite common for an engine to implement only part of the standard. |
| 8 | +Assim, é muito comum que um interpretador implemente apenas parte de um padrão. |
9 | 9 |
|
10 |
| -A good page to see the current state of support for language features is <https://kangax.github.io/compat-table/es6/> (it's big, we have a lot to study yet). |
| 10 | +Uma boa página para se ver o estágio atual de suporte de funcionalidades da linguagem é <https://compat-table.github.io/compat-table/es6/> (é extensa, nós ainda temos muito que estudar). |
11 | 11 |
|
12 |
| -As programmers, we'd like to use most recent features. The more good stuff - the better! |
| 12 | +Como programadores, nós gostaríamos de usar as funcionalidades mais recentes. Quantas mais forem as coisas boas - melhor! |
13 | 13 |
|
14 |
| -On the other hand, how to make our modern code work on older engines that don't understand recent features yet? |
| 14 | +Por outro lado, como fazer o nosso código moderno funcionar em interpretadores antigos que ainda não compreendam as funcionalidades recentes? |
15 | 15 |
|
16 |
| -There are two tools for that: |
| 16 | +Existem duas ferramentas para isso: |
17 | 17 |
|
18 | 18 | 1. Transpilers.
|
19 | 19 | 2. Polyfills.
|
20 | 20 |
|
21 |
| -Here, in this chapter, our purpose is to get the gist of how they work, and their place in web development. |
| 21 | +Aqui, neste capítulo, o nosso propósito é obter o essencial de como elas funcionam, e o seu lugar no desenvolvimento para a web. |
22 | 22 |
|
23 | 23 | ## Transpilers
|
24 | 24 |
|
25 |
| -A [transpiler](https://en.wikipedia.org/wiki/Source-to-source_compiler) is a special piece of software that translates source code to another source code. It can parse ("read and understand") modern code and rewrite it using older syntax constructs, so that it'll also work in outdated engines. |
| 25 | +Um [transpiler (transpilador em português)](https://en.wikipedia.org/wiki/Source-to-source_compiler) é uma peça especial de software que traduz um código-fonte para outro código-fonte. Ele pode analisar ("ler e compreender") código moderno, e o reescrever usando construções sintáticas antigas, de tal forma que também funcione em interpretadores desatualizados. |
26 | 26 |
|
27 |
| -E.g. JavaScript before year 2020 didn't have the "nullish coalescing operator" `??`. So, if a visitor uses an outdated browser, it may fail to understand the code like `height = height ?? 100`. |
| 27 | +Por exemplo, o JavaScript antes de 2020 não tinha o "operador de coalescência nula" `??`. Assim, se um visitante usar um navegador desatualizado, este não conseguirá compreender código como `height = height ?? 100`. |
28 | 28 |
|
29 |
| -A transpiler would analyze our code and rewrite `height ?? 100` into `(height !== undefined && height !== null) ? height : 100`. |
| 29 | +Um transpiler iria analisar o nosso código e reescrever `height ?? 100` para `(height !== undefined && height !== null) ? height : 100`. |
30 | 30 |
|
31 | 31 | ```js
|
32 |
| -// before running the transpiler |
| 32 | +// antes de correr o transpiler |
33 | 33 | height = height ?? 100;
|
34 | 34 |
|
35 |
| -// after running the transpiler |
| 35 | +// depois de correr o transpiler |
36 | 36 | height = (height !== undefined && height !== null) ? height : 100;
|
37 | 37 | ```
|
38 | 38 |
|
39 |
| -Now the rewritten code is suitable for older JavaScript engines. |
| 39 | +Agora, o código reescrito está adequado a interpretadores de JavaScript antigos. |
40 | 40 |
|
41 |
| -Usually, a developer runs the transpiler on their own computer, and then deploys the transpiled code to the server. |
| 41 | +Geralmente, um desenvolvedor executa o transpiler na sua própria máquina, e depois coloca o código transpilado no servidor. |
42 | 42 |
|
43 |
| -Speaking of names, [Babel](https://babeljs.io) is one of the most prominent transpilers out there. |
| 43 | +Falando em nomes, o [Babel](https://babeljs.io) é um dos mais prominentes transpilers por aí. |
44 | 44 |
|
45 |
| -Modern project build systems, such as [webpack](https://webpack.js.org/), provide a means to run a transpiler automatically on every code change, so it's very easy to integrate into the development process. |
| 45 | +Sistemas para a construção de projetos modernos, tais como o [webpack](https://webpack.js.org/), fornecem meios para automaticamente correr o transpiler em cada alteração do código, e assim é muito fácil o integrar no processo de desenvolvimento. |
46 | 46 |
|
47 | 47 | ## Polyfills
|
48 | 48 |
|
49 |
| -New language features may include not only syntax constructs and operators, but also built-in functions. |
| 49 | +Novas funcionalidades da linguagem podem incluir não só construções sintáticas e operadores, mas também funções incorporadas. |
50 | 50 |
|
51 |
| -For example, `Math.trunc(n)` is a function that "cuts off" the decimal part of a number, e.g `Math.trunc(1.23)` returns `1`. |
| 51 | +Por exemplo, `Math.trunc(n)` é uma função que "corta" a parte decimal de um número, ex. `Math.trunc(1.23) = 1` retorna 1. |
52 | 52 |
|
53 |
| -In some (very outdated) JavaScript engines, there's no `Math.trunc`, so such code will fail. |
| 53 | +Em alguns (muito desatualizados) interpretadores de JavaScript, não existe `Math.trunc`, por isto esse código irá falhar. |
54 | 54 |
|
55 |
| -As we're talking about new functions, not syntax changes, there's no need to transpile anything here. We just need to declare the missing function. |
| 55 | +Como estamos falando de novas funções, e não de alterações sintáticas, não é necessário transpilar nada aqui. Nós, apenas precisamos de declarar a função em falta. |
56 | 56 |
|
57 |
| -A script that updates/adds new functions is called "polyfill". It "fills in" the gap and adds missing implementations. |
| 57 | +Um script que atualize/adicione novas funções é chamado de "polyfill". Ele "preenche" o intervalo e adiciona implementações que faltem. |
58 | 58 |
|
59 |
| -For this particular case, the polyfill for `Math.trunc` is a script that implements it, like this: |
| 59 | +Para o caso em particular, o polyfill para `Math.trunc` é um script que o implementa, como aqui: |
60 | 60 |
|
61 | 61 | ```js
|
62 |
| -if (!Math.trunc) { // if no such function |
63 |
| - // implement it |
| 62 | +if (!Math.trunc) { // se a função não existir |
| 63 | + // implemente-a |
64 | 64 | Math.trunc = function(number) {
|
65 |
| - // Math.ceil and Math.floor exist even in ancient JavaScript engines |
66 |
| - // they are covered later in the tutorial |
| 65 | + // Math.ceil e Math.floor existem mesmo em interpretadores de JavaScript antigos |
| 66 | + // elas são estudadas mais adiante neste tutorial |
67 | 67 | return number < 0 ? Math.ceil(number) : Math.floor(number);
|
68 | 68 | };
|
69 | 69 | }
|
70 | 70 | ```
|
71 | 71 |
|
72 |
| -JavaScript is a highly dynamic language. Scripts may add/modify any function, even built-in ones. |
| 72 | +O JavaScript é uma linguagem altamente dinâmica. Scripts podem adicionar/modificar quaisquer funções, incluindo até incorporadas. |
73 | 73 |
|
74 |
| -Two interesting polyfill libraries are: |
75 |
| -- [core js](https://github.com/zloirock/core-js) that supports a lot, allows to include only needed features. |
76 |
| -- [polyfill.io](https://polyfill.io/) service that provides a script with polyfills, depending on the features and user's browser. |
| 74 | +Duas interessantes bibliotecas de polyfills são: |
| 75 | +- [core js](https://github.com/zloirock/core-js) que suporta muitas funcionalidades, e permite apenas incluir aquelas necessárias. |
| 76 | +- [polyfill.io](http://polyfill.io) um serviço que fornece um script com polyfills, dependendo das funcionalidades e do navegador do utilizador. |
77 | 77 |
|
| 78 | +## Resumo |
78 | 79 |
|
79 |
| -## Summary |
| 80 | +Neste capítulo, gostaríamos de o motivar a estudar funcionalidades modernas ou até em esboço da linguagem, mesmo que elas ainda não tenham um bom suporte pelos interpretadores de JavaScript. |
80 | 81 |
|
81 |
| -In this chapter we'd like to motivate you to study modern and even "bleeding-edge" language features, even if they aren't yet well-supported by JavaScript engines. |
| 82 | +Apenas não se esqueça de usar um transpiler (se empregar sintaxe ou operadores modernos) e polyfills (para adicionar funções que possam estar ausentes). E eles irão garantir que o código funcione. |
82 | 83 |
|
83 |
| -Just don't forget to use a transpiler (if using modern syntax or operators) and polyfills (to add functions that may be missing). They'll ensure that the code works. |
| 84 | +Por exemplo, mais adiante quando estiver familiarizado com o JavaScript, você pode configurar um sistema para a construção de código com base no [webpack](https://webpack.js.org/) e com o plugin [babel-loader](https://github.com/babel/babel-loader). |
84 | 85 |
|
85 |
| -For example, later when you're familiar with JavaScript, you can setup a code build system based on [webpack](https://webpack.js.org/) with the [babel-loader](https://github.com/babel/babel-loader) plugin. |
86 |
| -
|
87 |
| -Good resources that show the current state of support for various features: |
88 |
| -- <https://kangax.github.io/compat-table/es6/> - for pure JavaScript. |
89 |
| -- <https://caniuse.com/> - for browser-related functions. |
90 |
| -
|
91 |
| -P.S. Google Chrome is usually the most up-to-date with language features, try it if a tutorial demo fails. Most tutorial demos work with any modern browser though. |
| 86 | +Bons recursos que mostram o estágio atual do suporte para várias funcionalidades: |
| 87 | +- <https://compat-table.github.io/compat-table/es6/> - para puro JavaScript. |
| 88 | +- <https://caniuse.com/> - para funções com relação ao navegador. |
92 | 89 |
|
| 90 | +P.S. O Google Chrome, geralmente é o mais atualizado relativamente a funcionalidades da linguagem, experimente-o se um exemplo no tutorial falhar. Contudo, a maioria dos exemplos no tutorial funcionam com qualquer navegador moderno. |
0 commit comments