Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 25 additions & 25 deletions 1-js/03-code-quality/06-polyfills/article.md
Original file line number Diff line number Diff line change
@@ -1,57 +1,57 @@

# Polyfills
# Полифил
Comment thread
Kichikahunov marked this conversation as resolved.
Outdated

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](http://www.ecma-international.org/publications/standards/Ecma-262.htm).
JavaScript - динамично развивающийся язык программирования. Регулярно появляются новые предложения, они анализируются и, если предложения одобряются, их переносят в черновик <https://tc39.github.io/ecma262/>, а затем публикуют в [спецификации](http://www.ecma-international.org/publications/standards/Ecma-262.htm).

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.
Разработчики JavaScript движков сами принимают решение какие предложения реализовать в первую очередь. Они могут заранее реализовать функции, которые находятся в черновике и отложить разработку функций, которые уже перенесены в спецификацию, всё потому что некоторые функции могут быть менее интересны разработчикам, а может их сложнее реализовать.
Comment thread
Kichikahunov marked this conversation as resolved.
Outdated
Comment thread
Kichikahunov marked this conversation as resolved.
Outdated

So it's quite common for an engine to implement only the part of the standard.
Таким образом, довольно часто реализуется только часть стандарта.

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).
Можно проверить текущее состояние поддержки различных JavaScript функций на странице <https://kangax.github.io/compat-table/es6/> (нам предстоит многое ещё изучить).
Comment thread
Kichikahunov marked this conversation as resolved.
Outdated

## Babel

When we use modern features of the language, some engines may fail to support such code. Just as said, not all features are implemented everywhere.
Когда мы используем современные JavaScript функции, некоторые движки могут не поддерживать их. Как и было сказано выше, не все функции могут поддерживаться различными движками.
Comment thread
Kichikahunov marked this conversation as resolved.
Outdated

Here Babel comes to the rescue.
И тут приходит на помощь Babel.

[Babel](https://babeljs.io) is a [transpiler](https://en.wikipedia.org/wiki/Source-to-source_compiler). It rewrites modern JavaScript code into the previous standard.
[Babel](https://babeljs.io) - это [транспилер](https://en.wikipedia.org/wiki/Source-to-source_compiler). Он переписывает современные JavaScript функции в предыдущий стандарт.
Comment thread
Kichikahunov marked this conversation as resolved.
Outdated

Actually, there are two parts in Babel:
На самом деле, есть две части Babel:

1. First, the transpiler program, which rewrites the code. The developer runs it on their own computer. It rewrites the code into the older standard. And then the code is delivered to the website for users. Modern project build system like [webpack](http://webpack.github.io/) or [brunch](http://brunch.io/) provide means to run transpiler automatically on every code change, so that doesn't involve any time loss from our side.
1. Во-первых, транспилер, который переписывает код. Разработчик запускает Babel на своём компьютере. Он переписывает код в старый стандарт. И после, код отправляется на сайт. Современные сборщики проектов, такие как [webpack](http://webpack.github.io/) или [brunch](http://brunch.io/), предоставляют возможность запускать транспилер автоматически, после каждого изменения кода, что позволяет экономить время.

2. Second, the polyfill.
2. Во-вторых, полифил.

The transpiler rewrites the code, so syntax features are covered. But for new functions we need to write a special script that implements them. JavaScript is a highly dynamic language, scripts may not just add new functions, but also modify built-in ones, so that they behave according to the modern standard.
Транспилер переписывает код, поэтому синтаксис сохраняется. Но для новых функций нам необходимо написать скрипт, который будет поддерживать их. JavaScript - гибкий язык программирования, скрипты могут не только содержать новые функции, но и могут расширять встроенные, таким образом можно реализовать поддержку современного стандарта.
Comment thread
Kichikahunov marked this conversation as resolved.
Outdated

There's a term "polyfill" for scripts that "fill in" the gap and add missing implementations.
Термин "полифил" означает, что скрипт "заполняет" пробелы и добавляет современные функции.

Two interesting polyfills are:
- [babel polyfill](https://babeljs.io/docs/usage/polyfill/) that supports a lot, but is big.
- [polyfill.io](http://polyfill.io) service that allows to load/construct polyfills on-demand, depending on the features we need.
Два интересных полифила:
- [babel polyfill](https://babeljs.io/docs/usage/polyfill/) поддерживает много функций, но очень большой.
- [polyfill.io](http://polyfill.io) сервис, который позволяет загружать/конструировать полифилы в зависимости от необходимых функций.
Comment thread
Kichikahunov marked this conversation as resolved.
Outdated

So, we need to setup the transpiler and add the polyfill for old engines to support modern features.
Таким образом, чтобы современные функции поддерживались в старых движках, нам надо установить транспилер и добавить полифил.

If we orient towards modern engines and do not use features except those supported everywhere, then we don't need to use Babel.
Если мы ориентируемся на современные движки и не используем функции, которые не везде поддерживаются, то нам не нужен Babel.
Comment thread
Kichikahunov marked this conversation as resolved.
Outdated

## Examples in the tutorial
## Примеры в учебнике


````online
Most examples are runnable at-place, like this:
Большинство примеров можно запустить, как этот:
Comment thread
Kichikahunov marked this conversation as resolved.
Outdated
Comment thread
Kichikahunov marked this conversation as resolved.
Outdated

```js run
alert('Press the "Play" button in the upper-right corner to run');
alert('Нажмите кнопку "Play", в крайнем правом углу, чтобы запустить пример');
Comment thread
Kichikahunov marked this conversation as resolved.
Outdated
```

Examples that use modern JS will work only if your browser supports it.
Примеры, в которых используются современные JS функции, будут работать, если ваш браузер их поддерживает.
Comment thread
Kichikahunov marked this conversation as resolved.
Outdated
````

```offline
As you're reading the offline version, examples are not runnable. But they usually work :)
Пример можно запустить только, если вы подключены к сети интернет. Обычно этого не требуется :)
Comment thread
Kichikahunov marked this conversation as resolved.
Outdated
Comment thread
Kichikahunov marked this conversation as resolved.
Outdated
```

[Chrome Canary](https://www.google.com/chrome/browser/canary.html) is good for all examples, but other modern browsers are mostly fine too.
Для запуска примеров можно использовать [Chrome Canary](https://www.google.com/chrome/browser/canary.html), но подойдёт и любой другой современный браузер.
Comment thread
Kichikahunov marked this conversation as resolved.
Outdated

Note that on production we can use Babel to translate the code into suitable for less recent browsers, so there will be no such limitation, the code will run everywhere.
Обратите внимание, что для боевого сервера мы можем использовать Babel, чтобы переписывать код в подходящий для нескольких предыдущий версий браузеров. Поэтому, использовать определенную версию браузера не обязательно, код будет работать везде.
Comment thread
Kichikahunov marked this conversation as resolved.
Outdated