├── .gitignore ├── package.json ├── translations ├── zh-Hans │ ├── README.md │ └── user-handbook.md ├── zh-Hant │ ├── README.md │ └── user-handbook.md ├── ja │ ├── README.md │ └── user-handbook.md ├── ko │ ├── README.md │ └── user-handbook.md ├── he │ └── README.md ├── cs │ ├── README.md │ └── user-handbook.md ├── sv-SE │ └── README.md ├── sk-SK │ └── README.md ├── fi │ ├── README.md │ └── user-handbook.md ├── nl │ └── README.md ├── tr │ └── README.md ├── de │ └── README.md ├── af │ └── README.md ├── ar │ └── README.md ├── da │ └── README.md ├── hu │ └── README.md ├── no │ └── README.md ├── pt-BR │ └── README.md ├── ru │ └── README.md ├── vi │ └── README.md ├── fa-IR │ └── README.md ├── sr │ └── README.md ├── pl │ └── README.md ├── fr │ └── README.md ├── ro │ └── README.md ├── en │ └── README.md ├── uk │ └── README.md ├── ca │ └── README.md ├── es-ES │ └── README.md ├── pt-PT │ └── README.md ├── id-ID │ └── README.md ├── it │ └── README.md └── el │ └── README.md ├── crowdin.yaml ├── CONTRIBUTING.md ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | *.log 3 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "babel-handbook", 3 | "version": "1.0.0", 4 | "description": "How to Babel", 5 | "repository": "thejameskyle/babel-handbook.git", 6 | "homepage": "https://github.com/thejameskyle/babel-handbook", 7 | "keywords": [ 8 | "documentation", 9 | "guide", 10 | "handbook", 11 | "babel", 12 | "plugin" 13 | ], 14 | "author": "James Kyle ", 15 | "license": "cc-by-4.0" 16 | } 17 | -------------------------------------------------------------------------------- /translations/zh-Hans/README.md: -------------------------------------------------------------------------------- 1 | # Babel 手册 2 | 3 | 这本手册分为两个部分: 4 | 5 | * [用户手册](user-handbook.md)-如何安装/配置 Babel 及相关内容。 6 | * [插件手册](plugin-handbook.md)-如何为 Babel 创建插件。 7 | 8 | > 在 Twitter 上关注 [@thejameskyle](https://twitter.com/thejameskyle),第一时间获取更新。 9 | 10 | 如果你正在阅读本手册的非英语版本,你或许会发现一些英文的部分还没有被翻译。 如果你想帮助翻译的话你需要通过 Crowdin 来完成。 请先阅读[贡献指导](/CONTRIBUTING.md)来了解这方面更多的信息。 你会发现有些英语单词代表特定的编程概念。 如果按照字面翻译这些单词会导致在阅读时缺乏一致性和流畅性。 在此情形下,字面翻译会写在原文后面的 `()` 内。 例如:抽象语法树(ASTs) -------------------------------------------------------------------------------- /translations/zh-Hant/README.md: -------------------------------------------------------------------------------- 1 | # Babel 使用手冊 2 | 3 | 本手冊分為兩部分: 4 | 5 | * [使用者手冊](user-handbook.md) - 如何安裝與配置 Babel 6 | * [外掛手冊](plugin-handbook.md) - 如何撰寫 Babel 的外掛程式 7 | 8 | > 進一步的最新資訊,請追蹤[@thejameskyle](https://twitter.com/thejameskyle)的 Twitter 帳號。 9 | 10 | 如果你正在閱讀這份非英語版的手冊,你會發現其中仍有尚未翻譯完成的部分。 如果你想協助翻譯這份文件,你得透過 Crowdin 來參與。 詳情請參閱 [協助準則](/CONTRIBUTING.md)。 在過程中,你將會遇到許多程式設計上的專用術語, 如果按字面上的意義來直譯,會讓人覺得閱讀起來缺乏連貫性與流暢性。 在大多數情況下,你可在該術語的翻譯之後,加上`()`並附上英文原文。 例如: 抽象語法樹 (Abstract Syntax Tree, ASTs). -------------------------------------------------------------------------------- /translations/ja/README.md: -------------------------------------------------------------------------------- 1 | # Babel Handbook 2 | 3 | このハンドブックは2つの資料に分かれています。 4 | 5 | * [User Handbook](user-handbook.md) - Babel等のセットアップと設定について 6 | * [Plugin Handbook](plugin-handbook.md) - Babelのプラグイン作成について 7 | 8 | > 最新の情報を受け取るには、Twitterで[@thejameskyle](https://twitter.com/thejameskyle)をフォローしてください。 9 | 10 | 英語以外の翻訳版ハンドブックには、まだ翻訳されていない英語の文章があるかもしれません。 もし翻訳プロジェクトに参加いただける場合には、Crowdinを利用してください。 より詳しい情報は[貢献のためのガイドライン](/CONTRIBUTING.md)を参照してください。 あなたはプログラミング概念の中で多くの英単語を見るでしょう。 これらの英単語は、他の言語に翻訳してしまうと文章の一貫性と流暢さが損なわれる事となります。 多くの場合は逐語訳の後に`()`の中に元の英単語が書いてあります。 例えば:抽象構文木(ASTs) -------------------------------------------------------------------------------- /translations/ko/README.md: -------------------------------------------------------------------------------- 1 | # Babel Handbook 2 | 3 | 이 핸드북은 두 파트로 분리되어 있습니다: 4 | 5 | * [User Handbook](user-handbook.md) - Babel을 설치/운용 하는 방법과 여러가지 6 | * [Plugin Handbook](plugin-handbook.md) - Babel 플러그인을 만드는 방법 7 | 8 | > 향후 업데이트에 대한 내용은 Twitter의 [@thejameskyle](https://twitter.com/thejameskyle)를 팔로우하세요. 9 | 10 | 만약 영문 문서가 아닌 번역된 핸드북을 읽고 있다면, 여전히 번역되지 않은 영문 문서 섹션을 찾아 읽을 수 있습니다. 만약 다른 언어로 문서를 번역하고 싶다면 Crowdin을 통해 기여해야 합니다. 자세한 사항은 [기여 가이드](/CONTRIBUTING.md)를 참고하세요. 문서에서 프로그래밍의 개념적인 영문 단어들을 몇가지 찾을 수 있습니다. 이 문서는 번역된 문서이기 때문에 문서를 읽을 때 원문과 비교했을 때 일관성과 표현이 부족할 수 있습니다. 따라서 영문 그대로의 문장 또는 단어를 `()`에 그대로 넣은 경우를 많이 볼 수 있습니다. Abstract Syntax Trees (ASTs) 를 예시로 들 수 있습니다. -------------------------------------------------------------------------------- /translations/he/README.md: -------------------------------------------------------------------------------- 1 | # Babel Handbook 2 | 3 | This handbook is divided into two parts: 4 | 5 | * [User Handbook](user-handbook.md) - How to setup/configure Babel and more. 6 | * [Plugin Handbook](plugin-handbook.md) - How to create plugins for Babel. 7 | 8 | > For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) on Twitter. 9 | 10 | אם אתה קורא את המסמך הזה בגרסה מתורגמת, כלומר, שאיננה אנגלית, יכול להיות שתמצא חלקים שעוד לא תורגמו. אם תרצה לתרום לאחד התרגומים, עליך לעשות זאת דרך Crowdin. אנא תקרא את [כללי התרומה](/CONTRIBUTING.md) למידע נוסף. You will find a number of english words that are programming concepts. If these were translated to other languages there would be a lack of consistency and fluency when reading about them. In many cases you will find the literal translation followed by the english term in parenthesis `()`. For example: Abstract Syntax Trees (ASTs). -------------------------------------------------------------------------------- /translations/cs/README.md: -------------------------------------------------------------------------------- 1 | # Babel příručka 2 | 3 | Tato příručka je rozdělena do dvou částí: 4 | 5 | * [Uživatelská příručka](user-handbook.md) - Jak nainstalovat/konfigurovat Babel a další. 6 | * [Plugin příručka](plugin-handbook.md) - Jak vytvářet pluginy pro Babel. 7 | 8 | > Aktualizace sledujte na Twitteru: [@thejameskyle](https://twitter.com/thejameskyle). 9 | 10 | Pokud čtete neanglický překlad této příručky, stále můžete najít anglické části, které nebyly dosud přeloženy. Pokud byste chtěli přispět k jednomu z překladů musíte tak učinit prostřednictvím Crowdin. Přečtěte si prosím [pokyny pro přispívání](/CONTRIBUTING.md) pro další informace. Některé anglické výrazy vyjadřují programovací koncepty. Pokud by tyto výrazy byly přeloženy do jiných jazyků, vznikla by nekonzistence a čtení o nich by ztatilo plynulost. V mnoha případech najdete doslovný překlad, který následuje anglický výraz v závorkách `()`. Například: abstraktní syntaktické stromy (AST). -------------------------------------------------------------------------------- /translations/sv-SE/README.md: -------------------------------------------------------------------------------- 1 | # Babelhandbok 2 | 3 | Denna handbok är indelad i två delar: 4 | 5 | * [Användarhandbok](user-handbook.md) - installation/konfigurering av Babel och mycket mer. 6 | * [Pluginhandbok](plugin-handbook.md) - hur man skapar plugins för Babel. 7 | 8 | > För framtida uppdateringar, följ [@thejameskyle](https://twitter.com/thejameskyle) på Twitter. 9 | 10 | Om du läser en icke-engelsk översättning av denna handbok kan du fortfarande hitta sektioner som ännu inte har översatts. Om du vill bidra till en av översättningarna måste du göra det genom Crowdin. Läs [riktlinjerna för att bidra](/CONTRIBUTING.md) för mer information. Det används ett antal engelska ord som är programmeringsbegrepp. Om dessa översattes till andra språk skulle det finnas en brist på konsekvens och flyt när man läser om dem. I många fall hittar du den bokstavliga översättningen följt av den engelska termen i parentes `()`. Till exempel: abstrakt syntaxträd (ASTs). -------------------------------------------------------------------------------- /translations/sk-SK/README.md: -------------------------------------------------------------------------------- 1 | # Babel príručka 2 | 3 | Príručka je rozdelená do dvoch častí: 4 | 5 | * [Užívateľská príručka](user-handbook.md) - Ako nainštalovať/nakonfigurovať Babel a ďalšie. 6 | * [Príručka pluginov (rozšírení)](plugin-handbook.md) - Ako vytvárať pluginy pre Babel. 7 | 8 | > Aktualizácie sledujte na Twitteri [@thejameskyle](https://twitter.com/thejameskyle). 9 | 10 | Ak čítaš neanglický preklad tejto príručky, stále možeš nájsť anglické časti, ktoré zatiaľ neboli preložené. Ak by si chcel/a prispieť k jednému z prekladov, musíš to urobiť cez Crowdin. Pre viac informácií si prosím prečítaj [pravidlá prispievania](/CONTRIBUTING.md). Niektoré anglické výrazy vyjadrujú programovacie koncepty. Ak by sa tieto výrazy preložili do iných jazykov, vznikla by nekonzistencia a čítanie o nich by stratilo plynulosť. V mnoho prípadoch nájdeš doslovný preklad, za ktorým v zátvorkách `()` nasleduje anglický výraz. Napríklad: Abstraktné syntaktické stromy (AST). -------------------------------------------------------------------------------- /translations/fi/README.md: -------------------------------------------------------------------------------- 1 | # Babel -käsikirja 2 | 3 | Käsikirja koostuu kahdesta osasta: 4 | 5 | * [Käyttäjän käsikirja](user-handbook.md) - Babel asennus/konfigurinti ja lisäohjeita. 6 | * [Lisäosien käsikirja](plugin-handbook.md) - neuvoo lisäosien tekemisessä Babeliin. 7 | 8 | > Jos haluat pysyä ajantasalla, seuraa Twitterissä: [@thejameskyle](https://twitter.com/thejameskyle). 9 | 10 | Jos luet käännettyä (eli ei englanninkielistä) käsikirjaa, saatat kohdata edelleen alkuperäiskielellä kirjoitettuja kääntämättömiä osia. Jos haluat itse toimia kääntäjänä, käytä Crowdin -työkalua. Ole hyvä ja lue [vapaaehtoisten avustajien opas](/CONTRIBUTING.md) ennen osallistumista. Moni englanninkielinen termi liittyy ohjelmointiin. Jos nämä tekniset terkmit käännettäisiin suoraan muille kielille, tekstin oikeellisuus ja ymmärrettävyys kärsii. Monesti löydät suoraan alkuperäisen englanninkielisen termin ja sen lyhenteen sulkeissa `()`. Esimerkiksi: Abstract Syntax Trees (ASTs). -------------------------------------------------------------------------------- /translations/nl/README.md: -------------------------------------------------------------------------------- 1 | # Babel handboek 2 | 3 | Dit handboek is onderverdeeld in twee delen: 4 | 5 | * [Gebruikershandleiding](user-handbook.md) - hoe Babel in te stellen en te configureren. 6 | * [Plugin handboek](plugin-handbook.md) - hoe plugins voor Babel te maken. 7 | 8 | > Voor toekomstige updates, volg [@thejameskyle](https://twitter.com/thejameskyle) op Twitter. 9 | 10 | Als je een niet-Engelse vertaling van dit handboek leest, kun je Engelse delen tegenkomen die nog niet vertaald zijn. Als je wil bijdragen aan één van de vertalingen van dit document, moet je dat doen via Crowdin. Lees alsjeblieft de [bijdragerichtlijnen](/CONTRIBUTING.md) voor meer informatie. Nu en dan zal je Engelse programmeertermen tegenkomen. In dat geval is het logischer om de originele term te gebruiken om consistent te blijven. In de meeste gevallen zal je een letterlijke vertaling vinden, gevolgd door de Engelse term tussen haakjes `()`. bijvoorbeeld: Abstracte syntaxbomen (AST's). -------------------------------------------------------------------------------- /translations/tr/README.md: -------------------------------------------------------------------------------- 1 | # Babel El Kitabı 2 | 3 | Bu el kitabı iki bölümden oluşur: 4 | 5 | * [Kullanıcı el kitabı](user-handbook.md) - Kurulum yapılandırılması Babel ve daha fazlası. 6 | * [Eklenti el kitabı](plugin-handbook.md) - Babel için nasıl eklenti oluşturulur. 7 | 8 | > Gelecek güncellemeler için [@thejameskyle](https://twitter.com/thejameskyle)'i Twitter'dan takip edin. 9 | 10 | Eğer bu el kitabının İngilizce olmayan bir çevirisini okuyorsanız, halen çevrilmemiş bölümler görebilirsiniz. Eğer bu çevirilerden birine katkıda bulunmak istiyorsanız, bunu Crowdin aracılığıyla yapmalısınız. Lütfen daha fazla bilgi için [katkıda bulunma rehberi](/CONTRIBUTING.md)ne göz atın. Bazı programlama konseptlerinin İngilizce olarak yazıldığını göreceksiniz. Eğer bunlar diğer dillere çevirilir ise okumada tutarlılık ve akıcılık eksikliği olacaktır. Birçok durumda parantez içindeki ingilizce terimin edebi çevirisini bulacaksınız.`()`. Örneğin: Soyut Sözdizimi Ağaçları (ASTs). -------------------------------------------------------------------------------- /translations/de/README.md: -------------------------------------------------------------------------------- 1 | # Babel Handbuch 2 | 3 | Das Handbuch besteht aus zwei Teilen: 4 | 5 | * [Nutzerhandbuch](user-handbook.md) - Babel aufsetzen, konfigurieren und mehr. 6 | * [Plugin-Handbuch](plugin-handbook.md) - Plugins für Babel erstellen. 7 | 8 | > For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) on Twitter. 9 | 10 | Beim Lesen einer Übersetzung dieses Dokumentes, kann es sein, dass einige Kapitel noch nicht aus dem Englischen übersetzt worden sind. Um bei der Übersetzung mitzuhelfen kann dies mittels Crowdin durchgeführt werden. Für weitere Informationen bitte die [Regeln zur Mitarbeit](/CONTRIBUTING.md) lesen. You will find a number of english words that are programming concepts. If these were translated to other languages there would be a lack of consistency and fluency when reading about them. In many cases you will find the literal translation followed by the english term in parenthesis `()`. For example: Abstract Syntax Trees (ASTs). -------------------------------------------------------------------------------- /crowdin.yaml: -------------------------------------------------------------------------------- 1 | project_identifier: babel-plugin-handbook 2 | api_key_env: CROWDIN_API_KEY 3 | base_path: . 4 | files: 5 | - source: '/translations/en/**/*.md' 6 | translation: '/translations/%locale%/**/%original_file_name%' 7 | languages_mapping: 8 | locale: 9 | 'af': 'af' 10 | 'ar': 'ar' 11 | 'ca': 'ca' 12 | 'cs': 'cs' 13 | 'da': 'da' 14 | 'de': 'de' 15 | 'el': 'el' 16 | 'es-ES': 'es-ES' 17 | 'fi': 'fi' 18 | 'fr': 'fr' 19 | 'he': 'he' 20 | 'hu': 'hu' 21 | 'it': 'it' 22 | 'ja': 'ja' 23 | 'ko': 'ko' 24 | 'no': 'no' 25 | 'nl': 'nl' 26 | 'pl': 'pl' 27 | 'pt-BR': 'pt-BR' 28 | 'pt-PT': 'pt-PT' 29 | 'ro': 'ro' 30 | 'ru': 'ru' 31 | 'sr': 'sr' 32 | 'sv-SE': 'sv-SE' 33 | 'tr': 'tr' 34 | 'uk': 'uk' 35 | 'vi': 'vi' 36 | 'zh-CN': 'zh-Hans' 37 | 'zh-TW': 'zh-Hant' 38 | -------------------------------------------------------------------------------- /translations/af/README.md: -------------------------------------------------------------------------------- 1 | # Babel Handbook 2 | 3 | This handbook is divided into two parts: 4 | 5 | * [User Handbook](user-handbook.md) - How to setup/configure Babel and more. 6 | * [Plugin Handbook](plugin-handbook.md) - How to create plugins for Babel. 7 | 8 | > For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) on Twitter. 9 | 10 | If you are reading a non-english translation of this handbook you may still find english sections that have not yet been translated. If you would like to contribute to one of the translations you must do so through Crowdin. Please read the [contributing guidelines](/CONTRIBUTING.md) for more information. You will find a number of english words that are programming concepts. If these were translated to other languages there would be a lack of consistency and fluency when reading about them. In many cases you will find the literal translation followed by the english term in parenthesis `()`. For example: Abstract Syntax Trees (ASTs). -------------------------------------------------------------------------------- /translations/ar/README.md: -------------------------------------------------------------------------------- 1 | # Babel Handbook 2 | 3 | This handbook is divided into two parts: 4 | 5 | * [User Handbook](user-handbook.md) - How to setup/configure Babel and more. 6 | * [Plugin Handbook](plugin-handbook.md) - How to create plugins for Babel. 7 | 8 | > For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) on Twitter. 9 | 10 | If you are reading a non-english translation of this handbook you may still find english sections that have not yet been translated. If you would like to contribute to one of the translations you must do so through Crowdin. Please read the [contributing guidelines](/CONTRIBUTING.md) for more information. You will find a number of english words that are programming concepts. If these were translated to other languages there would be a lack of consistency and fluency when reading about them. In many cases you will find the literal translation followed by the english term in parenthesis `()`. For example: Abstract Syntax Trees (ASTs). -------------------------------------------------------------------------------- /translations/da/README.md: -------------------------------------------------------------------------------- 1 | # Babel Handbook 2 | 3 | This handbook is divided into two parts: 4 | 5 | * [User Handbook](user-handbook.md) - How to setup/configure Babel and more. 6 | * [Plugin Handbook](plugin-handbook.md) - How to create plugins for Babel. 7 | 8 | > For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) on Twitter. 9 | 10 | If you are reading a non-english translation of this handbook you may still find english sections that have not yet been translated. If you would like to contribute to one of the translations you must do so through Crowdin. Please read the [contributing guidelines](/CONTRIBUTING.md) for more information. You will find a number of english words that are programming concepts. If these were translated to other languages there would be a lack of consistency and fluency when reading about them. In many cases you will find the literal translation followed by the english term in parenthesis `()`. For example: Abstract Syntax Trees (ASTs). -------------------------------------------------------------------------------- /translations/hu/README.md: -------------------------------------------------------------------------------- 1 | # Babel Handbook 2 | 3 | This handbook is divided into two parts: 4 | 5 | * [User Handbook](user-handbook.md) - How to setup/configure Babel and more. 6 | * [Plugin Handbook](plugin-handbook.md) - How to create plugins for Babel. 7 | 8 | > For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) on Twitter. 9 | 10 | If you are reading a non-english translation of this handbook you may still find english sections that have not yet been translated. If you would like to contribute to one of the translations you must do so through Crowdin. Please read the [contributing guidelines](/CONTRIBUTING.md) for more information. You will find a number of english words that are programming concepts. If these were translated to other languages there would be a lack of consistency and fluency when reading about them. In many cases you will find the literal translation followed by the english term in parenthesis `()`. For example: Abstract Syntax Trees (ASTs). -------------------------------------------------------------------------------- /translations/no/README.md: -------------------------------------------------------------------------------- 1 | # Babel Handbook 2 | 3 | This handbook is divided into two parts: 4 | 5 | * [User Handbook](user-handbook.md) - How to setup/configure Babel and more. 6 | * [Plugin Handbook](plugin-handbook.md) - How to create plugins for Babel. 7 | 8 | > For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) on Twitter. 9 | 10 | If you are reading a non-english translation of this handbook you may still find english sections that have not yet been translated. If you would like to contribute to one of the translations you must do so through Crowdin. Please read the [contributing guidelines](/CONTRIBUTING.md) for more information. You will find a number of english words that are programming concepts. If these were translated to other languages there would be a lack of consistency and fluency when reading about them. In many cases you will find the literal translation followed by the english term in parenthesis `()`. For example: Abstract Syntax Trees (ASTs). -------------------------------------------------------------------------------- /translations/pt-BR/README.md: -------------------------------------------------------------------------------- 1 | # Babel Handbook 2 | 3 | Este manual está dividido em duas partes: 4 | 5 | * [Manual do usuário](user-handbook.md) - como configurar o Babel e muito mais. 6 | * [Manual de plugins](plugin-handbook.md) - como criar plugins para o Babel. 7 | 8 | > Para futuras atualizações, siga [@thejameskyle](https://twitter.com/thejameskyle) no Twitter. 9 | 10 | Se você está lendo uma tradução do Inglês deste manual, você pode encontrar seções inglês que ainda não foram traduzidas. Se você quiser contribuir com uma das traduções, você deve fazê-lo através do Crowdin. Por favor, leia as [orientações de contribuição](/CONTRIBUTING.md) para obter mais informações. Você encontrará algumas palavras em inglês que são conceitos de programação. Se estas foram traduzidas para outras línguas haveria uma falta de consistência e fluência ao ler. Em muitos casos, você irá encontrar a tradução literal, seguida do termo inglês em parênteses `()`. Por exemplo: árvores de sintaxe abstrata (ASTs). -------------------------------------------------------------------------------- /translations/ru/README.md: -------------------------------------------------------------------------------- 1 | # Справочник Babel 2 | 3 | Это руководство разделено на две части: 4 | 5 | * [Руководство Пользователя](user-handbook.md) - Установка и настройка Babel. 6 | * [Руководство Плагинов](plugin-handbook.md) - Создание плагинов для Babel. 7 | 8 | > Оставайтесь в курсе последних обовлений - подписывайтесь в Твиттере на [@thejameskyle](https://twitter.com/thejameskyle). 9 | 10 | Если вы читаете это не на английском языке, то вы можете наткнуться на разделы на английском, которые ещё не переведены. Если вы хотите помочь с переводом, то вы должны делать это, используя Crowdin. Прочтите, пожалуйста, [рекомендации](/CONTRIBUTING.md) для подробной информации. Также Вы можете встретить слова на английском, которые являются понятиями программирования. Они не были переведены умышленно, дабы сохранить удобство чтения и единство стиля. Хотя во многих случаях Вы найдете их буквальный перевод, а затем и их оригинал в скобках `()`. Например: Абстрактные Синтаксические Деревья (ASTs). -------------------------------------------------------------------------------- /translations/vi/README.md: -------------------------------------------------------------------------------- 1 | # Babel Handbook 2 | 3 | This handbook is divided into two parts: 4 | 5 | * [User Handbook](user-handbook.md) - How to setup/configure Babel and more. 6 | * [Plugin Handbook](plugin-handbook.md) - How to create plugins for Babel. 7 | 8 | > For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) on Twitter. 9 | 10 | If you are reading a non-english translation of this handbook you may still find english sections that have not yet been translated. If you would like to contribute to one of the translations you must do so through Crowdin. Please read the [contributing guidelines](/CONTRIBUTING.md) for more information. You will find a number of english words that are programming concepts. If these were translated to other languages there would be a lack of consistency and fluency when reading about them. In many cases you will find the literal translation followed by the english term in parenthesis `()`. For example: Abstract Syntax Trees (ASTs). -------------------------------------------------------------------------------- /translations/fa-IR/README.md: -------------------------------------------------------------------------------- 1 | # کتاب راهنمای Babel 2 | 3 | این کتاب راهنما به دو بخش تقسیم شده است: 4 | 5 | * [راهنمای کاربر](user-handbook.md) - نحوه ی آماده سازی و پیکربندی Babel و اطلاعات بیشتر. 6 | * [راهنمای Plugin](plugin-handbook.md) چگونه برای Babel افزونه ایجاد کنید. 7 | 8 | > برای به روز رسانی آینده [@thejameskyle](https://twitter.com/thejameskyle) را در توییتر دنبال کنید. 9 | 10 | اگر شما در حال خواندن ترجمه غیر انگلیسی این کتاب هستید، ممکن هست با بخشی مواجه شوید که هنوز ترجمه نشده باشد. اگر شما قصد دارید در کار ترجمه همکاری داشته باشید، باید از Crowdin برای اینکار استفاده کنید. لطفا [راهنمای همکاری](/CONTRIBUTING.md) را برای اطلاعات بیشتر مطالعه فرمائید. شما در حین ترجمه به تعدادی واژه انگلیسی که مفاهیم برنامه نویسی هستند، برخواهید خورد. اگر قصد ترجمه این واژه ها به زبان دیگری را داشتید، سعی کنید واژه های روان و سلیس را انتخاب کنید که خواننده به خوبی متوجه آنها شود. در بسیاری از موارد شما ترجمه تحت اللفظی از کلمه انگلیسی را در پرانتز `()` مشاهده خواهید کرد. به عنوان مثال: درخت نحو انتزاعی (ASTs). -------------------------------------------------------------------------------- /translations/sr/README.md: -------------------------------------------------------------------------------- 1 | # Вавилон Приручник 2 | 3 | Овај приручник је подељен у два дела: 4 | 5 | * [Кориснички Приручник](user-handbook.md) - Како да подесите/прилагодите Вавилон и више. 6 | * [Плагин Приручник](plugin-handbook.md) - Како да креирате плагинове за Вавилон. 7 | 8 | > За будућа ажурирања, пратите [@thejameskyle](https://twitter.com/thejameskyle) на Твитеру. 9 | 10 | Ако читате не-енглески превод овог приручника, још увек можете пронаћи делове на енглеском који још увек нису преведени. Ако желите да допринесете преводу на неки од других језика, морате то урадити кроз Crowdin. Молимо вас, прочитајте [водич за учешће](/CONTRIBUTING.md) за више информација. Пронаћи ћете одређен број енглеских речи које су програмерски концепти. Ако би се они преводили на друге језике, јавио би се недостатак конзистентности и течности када читате о њима. У највећем броју случајева, наћи ћете буквални превод праћен енглеским изразом у заградама `()`. На пример: Апстрактна синтаксна стабла (Abstract Syntax Trees). -------------------------------------------------------------------------------- /translations/pl/README.md: -------------------------------------------------------------------------------- 1 | # Babel Podręcznik 2 | 3 | Ten podręcznik jest podzielony na dwie części: 4 | 5 | * [Podręcznik Użytkownika](user-handbook.md) - Jak zainstalować/skonfigurować Babel i podobne. 6 | * [Podręcznik o Wtyczkach](plugin-handbook.md) - Jak stworzyć wtyczki dla Babel. 7 | 8 | > Po więcej informacji, śledź [@thejameskyle](https://twitter.com/thejameskyle) na Twitterze. 9 | 10 | Jeśli czytasz tłumaczenie tego podręcznika, nadal możesz znaleźć fragmenty po angielsku, które nie były jeszcze przetłumaczone. Jeśli chcesz przyłączyć się do tłumaczenia, musisz zrobić do przez platformę Crowdin. Przeczytaj proszę [wytyczne o współpracy](/CONTRIBUTING.md) po więcej informacji. Znajdziesz tutaj wiele angielskich słów, które są pojęciami w programowaniu. Jeśli były by one przetłumaczone na inny język, wystąpił by brak konsekwencji i zrozumieniu przy czytaniu o nich. W wielu przypadkach, znajdziesz dosłowne tłumaczenie i następujące po nim angielskie wyrażenie w nawiasach `()`. Na przykład: drzewo składniowe (ASTs). -------------------------------------------------------------------------------- /translations/fr/README.md: -------------------------------------------------------------------------------- 1 | # Manuel de Babel 2 | 3 | Ce manuel est divisé en deux parties : 4 | 5 | * [Manuel utilisateur](user-handbook.md) - Comment démarrer/configurer Babel et plus encore. 6 | * [Manuel des plugins](plugin-handbook.md) - Comment créer des plugins pour Babel. 7 | 8 | > Pour les prochaines mises à jour, suivez [@thejameskyle](https://twitter.com/thejameskyle) sur Twitter. 9 | 10 | Si vous êtes en train de lire une traduction de ce manuel, vous allez sûrement trouver des sections qui ne sont pas encore traduites. Si vous voulez contribuer à la traduction, vous pouvez le faire à l'aide du site Crowdin. Veuillez lire le [guide de contribution](/CONTRIBUTING.md) pour plus d'informations. Vous trouverez des mots anglais ou anglicisme qui sont des concepts de programmation. Ces concepts risque de perdre leurs sens une fois traduits dans une autre langue. Dans de nombreux cas vous trouverez une traduction littérale suivi du terme en anglais entre parenthèses `()`. Par exemple : Arbres de Syntaxe abstraite (ASTs). -------------------------------------------------------------------------------- /translations/ro/README.md: -------------------------------------------------------------------------------- 1 | # Manualul Babel 2 | 3 | Acest manual este împărţit în două părţi: 4 | 5 | * [Manualul utilizatorului](user-handbook.md) - modul de instalare/configurare Babel şi altele. 6 | * [Manualul pentru Plugin-uri](plugin-handbook.md) - cum se pot crea plugin-uri pentru Babel. 7 | 8 | > Pentru actualizări, urmăriţi-l pe [@thejameskyle](https://twitter.com/thejameskyle) pe Twitter. 9 | 10 | În cazul în care citiți într-o limbă diferită de engleză, este posibil ca unele secțiuni care nu au fost traduse incă, să le găsiți în engleză. Dacă doriți să contribuiți la traducerea acestui document, va trebui să folosiți Crowdin. Vă rugăm să citiți [ghidul de contribuție](/CONTRIBUTING.md) pentru mai multe informații. Veţi găsi cuvinte în limba engleză care sunt conceptele de programare. Dacă acestea ar fi traduse în alte limbi s-ar pierde consistența și fluența în citire. În anumite cazuri veți găsi traducerea literară urmată de termenul în engleză între paranteze `()`. De exemplu: Arbori Abstracți de Sintaxă (ASTs). -------------------------------------------------------------------------------- /translations/en/README.md: -------------------------------------------------------------------------------- 1 | # Babel Handbook 2 | 3 | This handbook is divided into two parts: 4 | 5 | - [User Handbook](user-handbook.md) - How to setup/configure Babel and more. 6 | - [Plugin Handbook](plugin-handbook.md) - How to create plugins for Babel. 7 | 8 | > For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) 9 | > on Twitter. 10 | 11 | If you are reading a non-english translation of this handbook you may still find 12 | english sections that have not yet been translated. If you would like to 13 | contribute to one of the translations you must do so through Crowdin. Please 14 | read the [contributing guidelines](/CONTRIBUTING.md) for more information. You 15 | will find a number of english words that are programming concepts. If these were 16 | translated to other languages there would be a lack of consistency and fluency 17 | when reading about them. In many cases you will find the literal translation 18 | followed by the english term in parenthesis `()`. For example: Abstract Syntax 19 | Trees (ASTs). 20 | -------------------------------------------------------------------------------- /translations/uk/README.md: -------------------------------------------------------------------------------- 1 | # Довідник Babel 2 | 3 | Цей довідник складається з двох частин: 4 | 5 | * [Довідник користувача](user-handbook.md) - Як встановити/налаштувати Babel та інше. 6 | * [Довідник розробника плагінів](plugin-handbook.md) - Як створювати плагіни для Babel. 7 | 8 | > Ви можете слідкувати за оновленнями в Twitter, підписавшись на [@thejameskyle](https://twitter.com/thejameskyle). 9 | 10 | Якщо ви читаєте не англійську версію цього довідника ви все одно можете зустріти секції англійською мовою які ще не перекладені. Ви можете приєднатись до роботи над перекладами за допомогою платформи Crowdin. Будь ласка, ознайомтесь із [довідкою перекладача](/CONTRIBUTING.md) для детальнішої інформації. Ви зустрінете цілий ряд англійських слів які описують концепції в програмуванні. Якщо вони будуть перекладені на інші мови це може спричинити непорозуміння, та зашкодити розумінню всього тексту. В багатьох випадках ви знайдете дослівний перклад поряд з оригінальною назвою в дужках `()`. Наприклад: Абстрактні Синтаксичні Дерева (ASTs). -------------------------------------------------------------------------------- /translations/ca/README.md: -------------------------------------------------------------------------------- 1 | # Manual de Babel 2 | 3 | Aquest manual està dividit en dues parts: 4 | 5 | * [Manual d'usuari](user-handbook.md) - Com configurar Babel i més. 6 | * [Manual d'extensions](plugin-handbook.md) - Com crear extensions per Babel. 7 | 8 | > Per a futures actualitzacions, segueix a [@*thejameskyle](https://twitter.com/thejameskyle) en Twitter. 9 | 10 | Si estàs llegint una traducció d'aquest manual, és possible que trobis seccions en anglès que encara no han estat traduïdes. Si desitja contribuir a una de les traduccions haurà de fer-ho a través de Crowdin. Per favor, llegeix les [directrius per contribuir](/CONTRIBUTING.md) per obtenir més informació. Trobaràs diverses paraules en anglès que es corresponen amb conceptes de programació. Si es traduïssin aquestes paraules a altres idiomes hi hauria una falta de consistència i fluïdesa en llegir una altra informació sobre elles. En molts casos trobaràs la traducció literal seguida del terme en anglès entre parèntesi `()`. Per exemple: Arbres de sintaxi abstracta (ASTs). -------------------------------------------------------------------------------- /translations/es-ES/README.md: -------------------------------------------------------------------------------- 1 | # Manual de Babel 2 | 3 | Este manual está dividido en dos partes: 4 | 5 | * [Manual de usuario](user-handbook.md) - Cómo configurar Babel y más. 6 | * [Manual de extensiones](plugin-handbook.md) - Cómo crear extensiones para Babel. 7 | 8 | > Para futuras actualizaciones, sigue a [@thejameskyle](https://twitter.com/thejameskyle) en Twitter. 9 | 10 | Si estás leyendo una traducción de este manual, es posible que encuentres secciones en inglés que aún no han sido traducidas. Si deseas contribuir a una de las traducciones deberás hacerlo a través de Crowdin. Por favor, lee las [directrices para contribuir](/CONTRIBUTING.md) para obtener más información. Encontrarás varias palabras en inglés que se corresponden con conceptos de programación. Si se tradujeran estas palabras a otros idiomas habría una falta de consistencia y fluidez al leer otra información sobre ellas. En muchos casos encontrarás la traducción literal seguida del término en inglés entre paréntesis `()`. Por ejemplo: Árboles de sintaxis abstracta (AST). -------------------------------------------------------------------------------- /translations/pt-PT/README.md: -------------------------------------------------------------------------------- 1 | # Manual de Babel 2 | 3 | Este manual está dividido em duas partes: 4 | 5 | * [Manual do utilizador](user-handbook.md) - Como configurar o Babel e mais. 6 | * [Manual de Plugins](plugin-handbook.md) - Como criar plugins para o Babel. 7 | 8 | > Para futuras atualizações, siga [@thejameskyle](https://twitter.com/thejameskyle) no Twitter. 9 | 10 | Se está a ler uma tradução não inglesa deste manual é possível que ainda encontre algumas secções em inglês que ainda não foram traduzidas. Se gostava de contribuir para uma das traduções terá de o fazer através do Crowdin. Por favor leia as [instruções para contribuir](/CONTRIBUTING.md) para mais informações. Irá encontrar uma série de palavras em Inglês que são conceitos de programação. Se estas palavras fossem traduzidas para outras línguas seria dificil de manter a consistência e coêrencia ao ler sobre elas. Em muitos casos, você irá encontrar a tradução literal, seguida do termo inglês em parênteses`()`. Por exemplo: Árvores de Sintaxe Abstractas (Abstract Syntax Trees). -------------------------------------------------------------------------------- /translations/id-ID/README.md: -------------------------------------------------------------------------------- 1 | # Paduan Babel 2 | 3 | Buku ini dibagi menjadi dua bagian: 4 | 5 | * [Pengguna Handbook](user-handbook.md) - bagaimana setup/konfigurasi Babel dan banyak lagi. 6 | * [Plugin Handbook](plugin-handbook.md) - bagaimana membuat plugin untuk Babel. 7 | 8 | > Untuk pembaruan terbaru, ikuti [@thejameskyle](https://twitter.com/thejameskyle) di Twitter. 9 | 10 | Jika anda membaca terjemahan non-inggris pada buku petunjuk ini, anda dapat menuju seksi bahasa inggris yang belum diterjemahkan. Jika anda ingin berkontribusi pada salah satu terjemahan, anda harus melakukannya melalui Crowdin. Mohon membaca [petunjuk kontribusi](/CONTRIBUTING.md) untuk informasi lebih lanjut. Anda akan menemukan sejumlah kata-kata bahasa Inggris yang adalah konsep-konsep pemrograman. Jika ini telah diterjemahkan ke bahasa lain akan ada kurangnya konsistensi dan kelancaran ketika membaca buku ini. Dalam banyak kasus, Anda akan menemukan terjemahan literal diikuti dengan istilah bahasa Inggris dalam kurung `()`. Sebagai contoh: Abstract Syntax Trees (ASTs). -------------------------------------------------------------------------------- /translations/it/README.md: -------------------------------------------------------------------------------- 1 | # Manuale di Babel 2 | 3 | Questo manuale è diviso in due parti: 4 | 5 | * [Manuale dell'utente](user-handbook.md) - Installazione/configurazione di Babel ed altro. 6 | * [Manuale dei plugins](plugin-handbook.md) - Come creare plugins per Babel. 7 | 8 | > Per aggiornamenti futuri, segui [@thejameskyle](https://twitter.com/thejameskyle) su Twitter. 9 | 10 | Nel caso in cui stiate leggendo questo documento in una lingua differente dall'inglese, potreste trovare sezioni in inglese ancora in attesa di traduzione. Se siete interessati a contribuire nella traduzione di questo documento, dovrete farlo attraverso Crowdin. Per maggiori informazioni, leggere la sezione [linee guida di contribuzione](/CONTRIBUTING.md). Troverete una serie di parole inglesi che sono concetti di programmazione. Se queste parole fossero tradotte in altre lingue, ci sarebbe una mancanza di coerenza e fluidità durante la lettura. In molti casi troverete la traduzione letterale, seguita dal termine inglese tra parentesi `()`. Ad esempio: Alberi Sintattici Astratti (ASTs). -------------------------------------------------------------------------------- /translations/el/README.md: -------------------------------------------------------------------------------- 1 | # Εγχειρίδιο Babel 2 | 3 | Αυτό το εγχειρίδιο χωρίζεται σε δύο μέρη: 4 | 5 | * [Εγχειρίδιο Χρήστη](user-handbook.md) - Πως να ρυθμίσετε το Babel και πολλά άλλα. 6 | * [Εγχειρίδιο Βυσμάτος (Plugin)](plugin-handbook.md) - Πως να δημιουργήσετε βύσματα (plugins) για το Babel. 7 | 8 | > Για μελλοντικές ενημερώσεις ακολουθήστε τον [@thejameskyle](https://twitter.com/thejameskyle) στο Twitter. 9 | 10 | Εαν διαβάζετε μια μη-αγγλική μετάφραση του παρόντος εγχειριδίου ίσως να βρείτε τμήματα του κειμένου στα αγγλικά, τα οποία δεν έχουν μεταφραστεί ακόμη. Αν θα θέλατε να συνεισφέρετε σε μια ή περισσότερες μεταφράσεις θα πρέπει να το κάνετε μέσω του Crowdin. Για περισσότερες πληροφορίες παρακαλώ διαβάστε τις [κατευθυντήριες γραμμές συνεισφοράς](/CONTRIBUTING.md). Θα βρείτε έναν αριθμό από αγγλικές λέξεις οι οποίες είναι προγραμματιστικές έννοιες. Αν μεταφραστούν σε άλλες γλώσσες θα υπάρξει ελλειψη συνέπειας και ευχέρειας κατά την ανάγνωση τους. Σε πολλές περιπτώσεις θα βρείτε την κυριολεκτική μετάφραση τους να ακολουθείτε από ένα αγγλικό όρο μέσα σε παρένθεση `()`. Για πάραδειγμα: Αφηρημένη Δενδροειδείς Σύνταξη (ΑΔΣ). -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ### Translating the handbook 4 | 5 | The English translation of this handbook is maintained in this repository, for 6 | other translations we use [Crowdin](https://crowdin.com/), if you would like to 7 | contribute to one of the translations you can invite yourself to the Crowdin 8 | Project [here](https://crowdin.com/project/babel-plugin-handbook/invite). 9 | 10 | Changes to the English translation will automatically be sent to Crowdin which 11 | will notify translators of changes. When translations are completed, they will be 12 | built and sent back to GitHub. There's a short delay, but if any part of this 13 | process does not happen, please open an issue. 14 | 15 | Once you set up your account on Crowdin you should be taken to 16 | [this page](https://crowdin.com/project/babel-plugin-handbook). 17 | 18 | Click on the language you would like to contribute to and then click on 19 | "README.md". You will be taken to the translation editor. 20 | 21 | ![Crowdin Translation Editor](https://cloud.githubusercontent.com/assets/952783/12076790/291e6cac-b170-11e5-989e-4cb2925e2b38.png) 22 | 23 | On the left side you can see the handbook. In red are missing translations, 24 | light green are translated, and dark green are translated and verified. 25 | 26 | If you click on one of the sections, it will bring it up in the center panel 27 | where you can enter a translation and save it. 28 | 29 | If you click on a section with text formatting or links, Crowdin has a special 30 | syntax for matching up the formatting. 31 | 32 | ![Crowdin translation format](https://cloud.githubusercontent.com/assets/952783/12076803/c1a83a52-b170-11e5-9925-329b129be959.png) 33 | 34 | If you match the numbered `<0>...` delimiters, Crowdin will build the final 35 | translation with all the formatting and links of the original. 36 | 37 | Once a translation is finished, it should only be a few minutes before the 38 | changes get pushed to GitHub automatically. 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Babel Handbook 2 | 3 | A guided handbook on how to use Babel and how to create plugins for Babel. 4 | 5 | **Translations** 6 | 7 | - [English](https://github.com/thejameskyle/babel-handbook/tree/master/translations/en/README.md) 8 | - [Afrikaans](https://github.com/thejameskyle/babel-handbook/tree/master/translations/af/README.md) 9 | - [العربية](https://github.com/thejameskyle/babel-handbook/tree/master/translations/ar/README.md) 10 | - [Català](https://github.com/thejameskyle/babel-handbook/tree/master/translations/ca/README.md) 11 | - [Čeština](https://github.com/thejameskyle/babel-handbook/tree/master/translations/cs/README.md) 12 | - [Dansk](https://github.com/thejameskyle/babel-handbook/tree/master/translations/da/README.md) 13 | - [Deutsch](https://github.com/thejameskyle/babel-handbook/tree/master/translations/de/README.md) 14 | - [Ελληνικά](https://github.com/thejameskyle/babel-handbook/tree/master/translations/el/README.md) 15 | - [Español](https://github.com/thejameskyle/babel-handbook/tree/master/translations/es-ES/README.md) 16 | - [فارسی](https://github.com/thejameskyle/babel-handbook/tree/master/translations/fa-IR/README.md) 17 | - [Français](https://github.com/thejameskyle/babel-handbook/tree/master/translations/fr/README.md) 18 | - [עִברִית](https://github.com/thejameskyle/babel-handbotree/master/ok/translations/he/README.md) 19 | - [Italiano](https://github.com/thejameskyle/babel-handbook/tree/master/translations/it/README.md) 20 | - [日本語](https://github.com/thejameskyle/babel-handbook/tree/master/translations/ja/README.md) 21 | - [한국어](https://github.com/thejameskyle/babel-handbook/tree/master/translations/ko/README.md) 22 | - [Magyar](https://github.com/thejameskyle/babel-handbook/tree/master/translations/hu/README.md) 23 | - [Nederlands](https://github.com/thejameskyle/babel-handbook/tree/master/translations/nl/README.md) 24 | - [Norsk](https://github.com/thejameskyle/babel-handbook/tree/master/translations/no/README.md) 25 | - [Polskie](https://github.com/thejameskyle/babel-handbook/tree/master/translations/pl/README.md) 26 | - [Português](https://github.com/thejameskyle/babel-handbook/tree/master/translations/pt-PT/README.md) 27 | - [Português (Brasil)](https://github.com/thejameskyle/babel-handbook/tree/master/translations/pt-BR/README.md) 28 | - [Română](https://github.com/thejameskyle/babel-handbook/tree/master/translations/ro/README.md) 29 | - [Русский](https://github.com/thejameskyle/babel-handbook/tree/master/translations/ru/README.md) 30 | - [Српски језик (Ћирилица)](https://github.com/thejameskyle/babel-handbook/tree/master/translations/sr/README.md) 31 | - [Suomi](https://github.com/thejameskyle/babel-handbook/tree/master/translations/fi/README.md) 32 | - [Svenska](https://github.com/thejameskyle/babel-handbook/tree/master/translations/sv-SE/README.md) 33 | - [Türkçe](https://github.com/thejameskyle/babel-handbook/tree/master/translations/tr/README.md) 34 | - [Tiếng Việt](https://github.com/thejameskyle/babel-handbook/tree/master/translations/vi/README.md) 35 | - [Українська](https://github.com/thejameskyle/babel-handbook/tree/master/translations/uk/README.md) 36 | - [中文](https://github.com/thejameskyle/babel-handbook/tree/master/translations/zh-Hans/README.md) 37 | - [繁體中文](https://github.com/thejameskyle/babel-handbook/tree/master/translations/zh-Hant/README.md) 38 | 39 | **[Request another translation](https://github.com/thejameskyle/babel-plugin-handbook/issues/new?title=Translation%20Request:%20[Please%20enter%20language%20here]&body=I%20am%20able%20to%20translate%20this%20language%20[yes/no])** 40 | 41 | If you are reading a non-English translation of this document you will find a 42 | number of English words that are programming concepts. If these were translated 43 | to other languages there would be a lack of consistency and fluency when reading 44 | about them. In many cases you will find the literal translation followed by the 45 | English term in parenthesis `()`. For example: Abstract Syntax Trees (ASTs). 46 | 47 | Special thanks to [@sebmck](https://github.com/sebmck/), 48 | [@hzoo](https://github.com/hzoo), 49 | [@jdalton](https://github.com/jdalton), 50 | [@abraithwaite](https://github.com/abraithwaite), 51 | [@robey](https://github.com/robey), and others for their 52 | amazing help on this handbook. 53 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Creative Commons Attribution 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution 4.0 International Public License 58 | 59 | By exercising the Licensed Rights (defined below), You accept and agree 60 | to be bound by the terms and conditions of this Creative Commons 61 | Attribution 4.0 International Public License ("Public License"). To the 62 | extent this Public License may be interpreted as a contract, You are 63 | granted the Licensed Rights in consideration of Your acceptance of 64 | these terms and conditions, and the Licensor grants You such rights in 65 | consideration of benefits the Licensor receives from making the 66 | Licensed Material available under these terms and conditions. 67 | 68 | 69 | Section 1 -- Definitions. 70 | 71 | a. Adapted Material means material subject to Copyright and Similar 72 | Rights that is derived from or based upon the Licensed Material 73 | and in which the Licensed Material is translated, altered, 74 | arranged, transformed, or otherwise modified in a manner requiring 75 | permission under the Copyright and Similar Rights held by the 76 | Licensor. For purposes of this Public License, where the Licensed 77 | Material is a musical work, performance, or sound recording, 78 | Adapted Material is always produced where the Licensed Material is 79 | synched in timed relation with a moving image. 80 | 81 | b. Adapter's License means the license You apply to Your Copyright 82 | and Similar Rights in Your contributions to Adapted Material in 83 | accordance with the terms and conditions of this Public License. 84 | 85 | c. Copyright and Similar Rights means copyright and/or similar rights 86 | closely related to copyright including, without limitation, 87 | performance, broadcast, sound recording, and Sui Generis Database 88 | Rights, without regard to how the rights are labeled or 89 | categorized. For purposes of this Public License, the rights 90 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 91 | Rights. 92 | 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. Share means to provide material to the public by any means or 116 | process that requires permission under the Licensed Rights, such 117 | as reproduction, public display, public performance, distribution, 118 | dissemination, communication, or importation, and to make material 119 | available to the public including in ways that members of the 120 | public may access the material from a place and at a time 121 | individually chosen by them. 122 | 123 | j. Sui Generis Database Rights means rights other than copyright 124 | resulting from Directive 96/9/EC of the European Parliament and of 125 | the Council of 11 March 1996 on the legal protection of databases, 126 | as amended and/or succeeded, as well as other essentially 127 | equivalent rights anywhere in the world. 128 | 129 | k. You means the individual or entity exercising the Licensed Rights 130 | under this Public License. Your has a corresponding meaning. 131 | 132 | 133 | Section 2 -- Scope. 134 | 135 | a. License grant. 136 | 137 | 1. Subject to the terms and conditions of this Public License, 138 | the Licensor hereby grants You a worldwide, royalty-free, 139 | non-sublicensable, non-exclusive, irrevocable license to 140 | exercise the Licensed Rights in the Licensed Material to: 141 | 142 | a. reproduce and Share the Licensed Material, in whole or 143 | in part; and 144 | 145 | b. produce, reproduce, and Share Adapted Material. 146 | 147 | 2. Exceptions and Limitations. For the avoidance of doubt, where 148 | Exceptions and Limitations apply to Your use, this Public 149 | License does not apply, and You do not need to comply with 150 | its terms and conditions. 151 | 152 | 3. Term. The term of this Public License is specified in Section 153 | 6(a). 154 | 155 | 4. Media and formats; technical modifications allowed. The 156 | Licensor authorizes You to exercise the Licensed Rights in 157 | all media and formats whether now known or hereafter created, 158 | and to make technical modifications necessary to do so. The 159 | Licensor waives and/or agrees not to assert any right or 160 | authority to forbid You from making technical modifications 161 | necessary to exercise the Licensed Rights, including 162 | technical modifications necessary to circumvent Effective 163 | Technological Measures. For purposes of this Public License, 164 | simply making modifications authorized by this Section 2(a) 165 | (4) never produces Adapted Material. 166 | 167 | 5. Downstream recipients. 168 | 169 | a. Offer from the Licensor -- Licensed Material. Every 170 | recipient of the Licensed Material automatically 171 | receives an offer from the Licensor to exercise the 172 | Licensed Rights under the terms and conditions of this 173 | Public License. 174 | 175 | b. No downstream restrictions. You may not offer or impose 176 | any additional or different terms or conditions on, or 177 | apply any Effective Technological Measures to, the 178 | Licensed Material if doing so restricts exercise of the 179 | Licensed Rights by any recipient of the Licensed 180 | Material. 181 | 182 | 6. No endorsement. Nothing in this Public License constitutes or 183 | may be construed as permission to assert or imply that You 184 | are, or that Your use of the Licensed Material is, connected 185 | with, or sponsored, endorsed, or granted official status by, 186 | the Licensor or others designated to receive attribution as 187 | provided in Section 3(a)(1)(A)(i). 188 | 189 | b. Other rights. 190 | 191 | 1. Moral rights, such as the right of integrity, are not 192 | licensed under this Public License, nor are publicity, 193 | privacy, and/or other similar personality rights; however, to 194 | the extent possible, the Licensor waives and/or agrees not to 195 | assert any such rights held by the Licensor to the limited 196 | extent necessary to allow You to exercise the Licensed 197 | Rights, but not otherwise. 198 | 199 | 2. Patent and trademark rights are not licensed under this 200 | Public License. 201 | 202 | 3. To the extent possible, the Licensor waives any right to 203 | collect royalties from You for the exercise of the Licensed 204 | Rights, whether directly or through a collecting society 205 | under any voluntary or waivable statutory or compulsory 206 | licensing scheme. In all other cases the Licensor expressly 207 | reserves any right to collect such royalties. 208 | 209 | 210 | Section 3 -- License Conditions. 211 | 212 | Your exercise of the Licensed Rights is expressly made subject to the 213 | following conditions. 214 | 215 | a. Attribution. 216 | 217 | 1. If You Share the Licensed Material (including in modified 218 | form), You must: 219 | 220 | a. retain the following if it is supplied by the Licensor 221 | with the Licensed Material: 222 | 223 | i. identification of the creator(s) of the Licensed 224 | Material and any others designated to receive 225 | attribution, in any reasonable manner requested by 226 | the Licensor (including by pseudonym if 227 | designated); 228 | 229 | ii. a copyright notice; 230 | 231 | iii. a notice that refers to this Public License; 232 | 233 | iv. a notice that refers to the disclaimer of 234 | warranties; 235 | 236 | v. a URI or hyperlink to the Licensed Material to the 237 | extent reasonably practicable; 238 | 239 | b. indicate if You modified the Licensed Material and 240 | retain an indication of any previous modifications; and 241 | 242 | c. indicate the Licensed Material is licensed under this 243 | Public License, and include the text of, or the URI or 244 | hyperlink to, this Public License. 245 | 246 | 2. You may satisfy the conditions in Section 3(a)(1) in any 247 | reasonable manner based on the medium, means, and context in 248 | which You Share the Licensed Material. For example, it may be 249 | reasonable to satisfy the conditions by providing a URI or 250 | hyperlink to a resource that includes the required 251 | information. 252 | 253 | 3. If requested by the Licensor, You must remove any of the 254 | information required by Section 3(a)(1)(A) to the extent 255 | reasonably practicable. 256 | 257 | 4. If You Share Adapted Material You produce, the Adapter's 258 | License You apply must not prevent recipients of the Adapted 259 | Material from complying with this Public License. 260 | 261 | 262 | Section 4 -- Sui Generis Database Rights. 263 | 264 | Where the Licensed Rights include Sui Generis Database Rights that 265 | apply to Your use of the Licensed Material: 266 | 267 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 268 | to extract, reuse, reproduce, and Share all or a substantial 269 | portion of the contents of the database; 270 | 271 | b. if You include all or a substantial portion of the database 272 | contents in a database in which You have Sui Generis Database 273 | Rights, then the database in which You have Sui Generis Database 274 | Rights (but not its individual contents) is Adapted Material; and 275 | 276 | c. You must comply with the conditions in Section 3(a) if You Share 277 | all or a substantial portion of the contents of the database. 278 | 279 | For the avoidance of doubt, this Section 4 supplements and does not 280 | replace Your obligations under this Public License where the Licensed 281 | Rights include other Copyright and Similar Rights. 282 | 283 | 284 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 285 | 286 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 287 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 288 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 289 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 290 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 291 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 292 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 293 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 294 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 295 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 296 | 297 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 298 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 299 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 300 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 301 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 302 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 303 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 304 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 305 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 306 | 307 | c. The disclaimer of warranties and limitation of liability provided 308 | above shall be interpreted in a manner that, to the extent 309 | possible, most closely approximates an absolute disclaimer and 310 | waiver of all liability. 311 | 312 | 313 | Section 6 -- Term and Termination. 314 | 315 | a. This Public License applies for the term of the Copyright and 316 | Similar Rights licensed here. However, if You fail to comply with 317 | this Public License, then Your rights under this Public License 318 | terminate automatically. 319 | 320 | b. Where Your right to use the Licensed Material has terminated under 321 | Section 6(a), it reinstates: 322 | 323 | 1. automatically as of the date the violation is cured, provided 324 | it is cured within 30 days of Your discovery of the 325 | violation; or 326 | 327 | 2. upon express reinstatement by the Licensor. 328 | 329 | For the avoidance of doubt, this Section 6(b) does not affect any 330 | right the Licensor may have to seek remedies for Your violations 331 | of this Public License. 332 | 333 | c. For the avoidance of doubt, the Licensor may also offer the 334 | Licensed Material under separate terms or conditions or stop 335 | distributing the Licensed Material at any time; however, doing so 336 | will not terminate this Public License. 337 | 338 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 339 | License. 340 | 341 | 342 | Section 7 -- Other Terms and Conditions. 343 | 344 | a. The Licensor shall not be bound by any additional or different 345 | terms or conditions communicated by You unless expressly agreed. 346 | 347 | b. Any arrangements, understandings, or agreements regarding the 348 | Licensed Material not stated herein are separate from and 349 | independent of the terms and conditions of this Public License. 350 | 351 | 352 | Section 8 -- Interpretation. 353 | 354 | a. For the avoidance of doubt, this Public License does not, and 355 | shall not be interpreted to, reduce, limit, restrict, or impose 356 | conditions on any use of the Licensed Material that could lawfully 357 | be made without permission under this Public License. 358 | 359 | b. To the extent possible, if any provision of this Public License is 360 | deemed unenforceable, it shall be automatically reformed to the 361 | minimum extent necessary to make it enforceable. If the provision 362 | cannot be reformed, it shall be severed from this Public License 363 | without affecting the enforceability of the remaining terms and 364 | conditions. 365 | 366 | c. No term or condition of this Public License will be waived and no 367 | failure to comply consented to unless expressly agreed to by the 368 | Licensor. 369 | 370 | d. Nothing in this Public License constitutes or may be interpreted 371 | as a limitation upon, or waiver of, any privileges and immunities 372 | that apply to the Licensor or You, including from the legal 373 | processes of any jurisdiction or authority. 374 | 375 | 376 | ======================================================================= 377 | 378 | Creative Commons is not a party to its public licenses. 379 | Notwithstanding, Creative Commons may elect to apply one of its public 380 | licenses to material it publishes and in those instances will be 381 | considered the "Licensor." Except for the limited purpose of indicating 382 | that material is shared under a Creative Commons public license or as 383 | otherwise permitted by the Creative Commons policies published at 384 | creativecommons.org/policies, Creative Commons does not authorize the 385 | use of the trademark "Creative Commons" or any other trademark or logo 386 | of Creative Commons without its prior written consent including, 387 | without limitation, in connection with any unauthorized modifications 388 | to any of its public licenses or any other arrangements, 389 | understandings, or agreements concerning use of licensed material. For 390 | the avoidance of doubt, this paragraph does not form part of the public 391 | licenses. 392 | 393 | Creative Commons may be contacted at creativecommons.org. 394 | -------------------------------------------------------------------------------- /translations/zh-Hans/user-handbook.md: -------------------------------------------------------------------------------- 1 | # Babel 用户手册 2 | 3 | 这本手册涵盖了关于 [Babel](https://babeljs.io) 的使用及其相关工具的内容。 4 | 5 | [![cc-by-4.0](https://licensebuttons.net/l/by/4.0/80x15.png)](http://creativecommons.org/licenses/by/4.0/) 6 | 7 | 这本手册提供了多种语言的版本,查看 [自述文件](/README.md) 里的完整列表。 8 | 9 | # 目录 10 | 11 | * [介绍](#toc-introduction) 12 | * [安装 Babel](#toc-setting-up-babel) 13 | * [`babel-cli`](#toc-babel-cli) 14 | * [在项目内运行 Babel CLI](#toc-running-babel-cli-from-within-a-project) 15 | * [`babel-register`](#toc-babel-register) 16 | * [`babel-node`](#toc-babel-node) 17 | * [`babel-core`](#toc-babel-core) 18 | * [配置 Babel](#toc-configuring-babel) 19 | * [`.babelrc`](#toc-babelrc) 20 | * [`babel-preset-es2015`](#toc-babel-preset-es2015) 21 | * [`babel-preset-react`](#toc-babel-preset-react) 22 | * [`babel-preset-stage-x`](#toc-babel-preset-stage-x) 23 | * [执行 Babel 生成的代码](#toc-executing-babel-generated-code) 24 | * [`babel-polyfill`](#toc-babel-polyfill) 25 | * [`babel-runtime`](#toc-babel-runtime) 26 | * [配置 Babel(进阶)](#toc-configuring-babel-advanced) 27 | * [手动指定插件](#toc-manually-specifying-plugins) 28 | * [插件选项](#toc-plugin-options) 29 | * [基于环境自定义 Babel](#toc-customizing-babel-based-on-environment) 30 | * [制作你自己的预设(preset)](#toc-making-your-own-preset) 31 | * [Babel 和其他工具](#toc-babel-and-other-tools) 32 | * [静态分析工具](#toc-static-analysis-tools) 33 | * [语法检查(Linting)](#toc-linting) 34 | * [代码风格](#toc-code-style) 35 | * [文档](#toc-documentation) 36 | * [框架](#toc-frameworks) 37 | * [React](#toc-react) 38 | * [文本编辑器和 IDEs(集成开发环境)](#toc-text-editors-and-ides) 39 | * [Babel 支持](#toc-babel-support) 40 | * [Babel 论坛](#toc-babel-forum) 41 | * [Babel 聊天](#toc-babel-chat) 42 | * [Babel 问题](#toc-babel-issues) 43 | * [创建漂亮的 Babel 错误报告](#toc-creating-an-awesome-babel-bug-report) 44 | 45 | # 介绍 46 | 47 | Babel 是一个通用的多用途 JavaScript 编译器。通过 Babel 你可以使用(并创建)下一代的 JavaScript,以及下一代的 JavaScript 工具。 48 | 49 | 作为一种语言,JavaScript 在不断发展,新的标准/提案和新的特性层出不穷。 在得到广泛普及之前,Babel 能够让你提前(甚至数年)使用它们。 50 | 51 | Babel 把用最新标准编写的 JavaScript 代码向下编译成可以在今天随处可用的版本。 这一过程叫做“源码到源码”编译, 也被称为转换编译(transpiling,是一个自造合成词,即转换+编译。以下也简称为转译)。 52 | 53 | 例如,Babel 能够将新的 ES2015 箭头函数语法: 54 | 55 | ```js 56 | const square = n => n * n; 57 | ``` 58 | 59 | 转译为: 60 | 61 | ```js 62 | const square = function square(n) { 63 | return n * n; 64 | }; 65 | ``` 66 | 67 | 不过 Babel 的用途并不止于此,它支持语法扩展,能支持像 React 所用的 JSX 语法,同时还支持用于静态类型检查的流式语法(Flow Syntax)。 68 | 69 | 更重要的是,Babel 的一切都是简单的插件,谁都可以创建自己的插件,利用 Babel 的全部威力去做任何事情。 70 | 71 | *再进一步*,Babel 自身被分解成了数个核心模块,任何人都可以利用它们来创建下一代的 JavaScript 工具。 72 | 73 | 已经有很多人都这样做了,围绕着 Babel 涌现出了非常大规模和多样化的生态系统。 在这本手册中,我将介绍如何使用 Babel 的内建工具以及一些来自于社区的非常有用的东西。 74 | 75 | > ***在 Twitter 上关注 [@thejameskyle](https://twitter.com/thejameskyle),第一时间获取更新。*** 76 | 77 | * * * 78 | 79 | # 安装 Babel 80 | 81 | 由于 JavaScript 社区没有统一的构建工具、框架、平台等等,因此 Babel 正式集成了对所有主流工具的支持。 从 Gulp 到 Browserify,从 Ember 到 Meteor,不管你的环境设置如何,Babel 都有正式的集成支持。 82 | 83 | 本手册的目的主要是介绍 Babel 内建方式的安装,不过你可以访问交互式的[安装页面](http://babeljs.io/docs/setup)来查看其它的整合方式。 84 | 85 | > **注意:** 本手册将涉及到一些命令行工具如 `node` 和 `npm`。在继续阅读之前请确保你已经熟悉这些工具了。 86 | 87 | ## `babel-cli` 88 | 89 | Babel 的 CLI 是一种在命令行下使用 Babel 编译文件的简单方法。 90 | 91 | 让我们先全局安装它来学习基础知识。 92 | 93 | ```sh 94 | $ npm install --global babel-cli 95 | ``` 96 | 97 | 我们可以这样来编译我们的第一个文件: 98 | 99 | ```sh 100 | $ babel my-file.js 101 | ``` 102 | 103 | 这将把编译后的结果直接输出至终端。使用 `--out-file` 或着 `-o` 可以将结果写入到指定的文件。. 104 | 105 | ```sh 106 | $ babel example.js --out-file compiled.js 107 | # 或 108 | $ babel example.js -o compiled.js 109 | ``` 110 | 111 | 如果我们想要把一个目录整个编译成一个新的目录,可以使用 `--out-dir` 或者 `-d`。. 112 | 113 | ```sh 114 | $ babel src --out-dir lib 115 | # 或 116 | $ babel src -d lib 117 | ``` 118 | 119 | ### 在项目内运行 Babel CLI 120 | 121 | 尽管你*可以*把 Babel CLI 全局安装在你的机器上,但是按项目逐个安装在**本地**会更好。 122 | 123 | 有两个主要的原因。 124 | 125 | 1. 在同一台机器上的不同项目或许会依赖不同版本的 Babel 并允许你有选择的更新。 126 | 2. 这意味着你对工作环境没有隐式依赖,这让你的项目有很好的可移植性并且易于安装。 127 | 128 | 要在(项目)本地安装 Babel CLI 可以运行: 129 | 130 | ```sh 131 | $ npm install --save-dev babel-cli 132 | ``` 133 | 134 | > **注意:**因为全局运行 Babel 通常不是什么好习惯所以如果你想要卸载全局安装的 Babel 的话,可以运行: 135 | > 136 | > ```sh 137 | $ npm uninstall --global babel-cli 138 | ``` 139 | 140 | 安装完成后,你的 `package.json` 应该如下所示: 141 | 142 | ```json 143 | { 144 | "name": "my-project", 145 | "version": "1.0.0", 146 | "devDependencies": { 147 | "babel-cli": "^6.0.0" 148 | } 149 | } 150 | ``` 151 | 152 | 现在,我们不直接从命令行运行 Babel 了,取而代之我们将把运行命令写在 **npm scripts** 里,这样可以使用 Babel 的本地版本。 153 | 154 | 只需将 `"scripts"` 字段添加到你的 `package.json` 文件内并且把 babel 命令写成 `build` 字段。. 155 | 156 | ```diff 157 | { 158 | "name": "my-project", 159 | "version": "1.0.0", 160 | + "scripts": { 161 | + "build": "babel src -d lib" 162 | + }, 163 | "devDependencies": { 164 | "babel-cli": "^6.0.0" 165 | } 166 | } 167 | ``` 168 | 169 | 现在可以在终端里运行: 170 | 171 | ```js 172 | npm run build 173 | ``` 174 | 175 | 这将以与之前同样的方式运行 Babel,但这一次我们使用的是本地副本。 176 | 177 | ## `babel-register` 178 | 179 | 下一个常用的运行 Babel 的方法是通过 `babel-register`。这种方法只需要引入文件就可以运行 Babel,或许能更好地融入你的项目设置。 180 | 181 | 但请注意这种方法并不适合正式产品环境使用。 直接部署用此方式编译的代码不是好的做法。 在部署之前预先编译会更好。 不过用在构建脚本或是其他本地运行的脚本中是非常合适的。 182 | 183 | 让我们先在项目中创建 `index.js` 文件。 184 | 185 | ```js 186 | console.log("Hello world!"); 187 | ``` 188 | 189 | 如果我们用 `node index.js` 来运行它是不会使用 Babel 来编译的。所以我们需要设置 `babel-register`。. 190 | 191 | 首先安装 `babel-register`。. 192 | 193 | ```sh 194 | $ npm install --save-dev babel-register 195 | ``` 196 | 197 | 接着,在项目中创建 `register.js` 文件并添加如下代码: 198 | 199 | ```js 200 | require("babel-register"); 201 | require("./index.js"); 202 | ``` 203 | 204 | 这样做可以把 Babel *注册*到 Node 的模块系统中并开始编译其中 `require` 的所有文件。 205 | 206 | 现在我们可以使用 `register.js` 来代替 `node index.js` 来运行了。 207 | 208 | ```sh 209 | $ node register.js 210 | ``` 211 | 212 | > **注意:**你不能在你要编译的文件内同时注册 Babel,因为 node 会在 Babel 编译它之前就将它执行了。 213 | > 214 | > ```js 215 | require("babel-register"); 216 | // 未编译的: 217 | console.log("Hello world!"); 218 | ``` 219 | 220 | ## `babel-node` 221 | 222 | 如果你要用 `node` CLI 来运行代码,那么整合 Babel 最简单的方式就是使用 `babel-node` CLI,它是 `node` CLI 的替代品。 223 | 224 | 但请注意这种方法并不适合正式产品环境使用。 直接部署用此方式编译的代码不是好的做法。 在部署之前预先编译会更好。 不过用在构建脚本或是其他本地运行的脚本中是非常合适的。 225 | 226 | 首先确保 `babel-cli` 已经安装了。 227 | 228 | ```sh 229 | $ npm install --save-dev babel-cli 230 | ``` 231 | 232 | > **注意:** 如果您想知道我们为什么要在本地安装,请阅读 上面[在项目内运行Babel CLI](#toc-running-babel-cli-from-within-a-project)的部分。 233 | 234 | 然后用 `babel-node` 来替代 `node` 运行所有的代码 。. 235 | 236 | 如果用 npm `scripts` 的话只需要这样做: 237 | 238 | ```diff 239 | { 240 | "scripts": { 241 | - "script-name": "node script.js" 242 | + "script-name": "babel-node script.js" 243 | } 244 | } 245 | ``` 246 | 247 | 要不然的话你需要写全 `babel-node` 的路径。 248 | 249 | ```diff 250 | - node script.js 251 | + ./node_modules/.bin/babel-node script.js 252 | ``` 253 | 254 | > 提示:你可以使用 [`npm-run`](https://www.npmjs.com/package/npm-run)。. 255 | 256 | ## `babel-core` 257 | 258 | 如果你需要以编程的方式来使用 Babel,可以使用 `babel-core` 这个包。 259 | 260 | 首先安装 `babel-core`。. 261 | 262 | ```sh 263 | $ npm install babel-core 264 | ``` 265 | 266 | ```js 267 | var babel = require("babel-core"); 268 | ``` 269 | 270 | 字符串形式的 JavaScript 代码可以直接使用 `babel.transform` 来编译。. 271 | 272 | ```js 273 | babel.transform("code();", options); 274 | // => { code, map, ast } 275 | ``` 276 | 277 | 如果是文件的话,可以使用异步 api: 278 | 279 | ```js 280 | babel.transformFile("filename.js", options, function(err, result) { 281 | result; // => { code, map, ast } 282 | }); 283 | ``` 284 | 285 | 或者是同步 api: 286 | 287 | ```js 288 | babel.transformFileSync("filename.js", options); 289 | // => { code, map, ast } 290 | ``` 291 | 292 | 要是已经有一个 Babel AST(抽象语法树)了就可以直接从 AST 进行转换。 293 | 294 | ```js 295 | babel.transformFromAst(ast, code, options); 296 | // => { code, map, ast } 297 | ``` 298 | 299 | 对于上述所有方法,`options` 指的都是 http://babeljs.io/docs/usage/options/ 300 | 301 | * * * 302 | 303 | # 配置 Babel 304 | 305 | 你或许已经注意到了,目前为止通过运行 Babel 自己我们并没能“翻译”代码,而仅仅是把代码从一处拷贝到了另一处。 306 | 307 | 这是因为我们还没告诉 Babel 要做什么。 308 | 309 | > 由于 Babel 是一个可以用各种花样去使用的通用编译器,因此默认情况下它反而什么都不做。你必须明确地告诉 Babel 应该要做什么。 310 | 311 | 你可以通过安装**插件(plugins)**或**预设(presets,也就是一组插件)**来指示 Babel 去做什么事情。 312 | 313 | ## `.babelrc` 314 | 315 | 在我们告诉 Babel 该做什么之前,我们需要创建一个配置文件。你需要做的就是在项目的根路径下创建 `.babelrc` 文件。然后输入以下内容作为开始: 316 | 317 | ```js 318 | { 319 | "presets": [], 320 | "plugins": [] 321 | } 322 | ``` 323 | 324 | 这个文件就是用来让 Babel 做你要它做的事情的配置文件。 325 | 326 | > **注意:**尽管你也可以用其他方式给 Babel 传递选项,但 `.babelrc` 文件是约定也是最好的方式。 327 | 328 | ## `babel-preset-es2015` 329 | 330 | 我们先从让 Babel 把 ES2015(最新版本的 JavaScript 标准,也叫做 ES6)编译成 ES5(现今在大多数 JavaScript 环境下可用的版本)开始吧。 331 | 332 | 我们需要安装 "es2015" Babel 预设: 333 | 334 | ```sh 335 | $ npm install --save-dev babel-preset-es2015 336 | ``` 337 | 338 | 我们修改 `.babelrc` 来包含这个预设。 339 | 340 | ```diff 341 | { 342 | "presets": [ 343 | + "es2015" 344 | ], 345 | "plugins": [] 346 | } 347 | ``` 348 | 349 | ## `babel-preset-react` 350 | 351 | 设置 React 一样容易。只需要安装这个预设: 352 | 353 | ```sh 354 | $ npm install --save-dev babel-preset-react 355 | ``` 356 | 357 | 然后在 `.babelrc` 文件里补充: 358 | 359 | ```diff 360 | { 361 | "presets": [ 362 | "es2015", 363 | + "react" 364 | ], 365 | "plugins": [] 366 | } 367 | ``` 368 | 369 | ## `babel-preset-stage-x` 370 | 371 | JavaScript 还有一些提案,正在积极通过 TC39(ECMAScript 标准背后的技术委员会)的流程成为标准的一部分。 372 | 373 | 这个流程分为 5(0-4)个阶段。 随着提案得到越多的关注就越有可能被标准采纳,于是他们就继续通过各个阶段,最终在阶段 4 被标准正式采纳。 374 | 375 | 以下是4 个不同阶段的(打包的)预设: 376 | 377 | * `babel-preset-stage-0` 378 | * `babel-preset-stage-1` 379 | * `babel-preset-stage-2` 380 | * `babel-preset-stage-3` 381 | 382 | > 注意 stage-4 预设是不存在的因为它就是上面的 `es2015` 预设。 383 | 384 | 以上每种预设都依赖于紧随的后期阶段预设。例如,`babel-preset-stage-1` 依赖 `babel-preset-stage-2`,后者又依赖 `babel-preset-stage-3`。. 385 | 386 | 使用的时候只需要安装你想要的阶段就可以了: 387 | 388 | ```sh 389 | $ npm install --save-dev babel-preset-stage-2 390 | ``` 391 | 392 | 然后添加进你的 `.babelrc` 配置文件。 393 | 394 | ```diff 395 | { 396 | "presets": [ 397 | "es2015", 398 | "react", 399 | + "stage-2" 400 | ], 401 | "plugins": [] 402 | } 403 | ``` 404 | 405 | * * * 406 | 407 | # 执行 Babel 生成的代码 408 | 409 | 即便你已经用 Babel 编译了你的代码,但这还不算完。 410 | 411 | ## `babel-polyfill` 412 | 413 | Babel 几乎可以编译所有时新的 JavaScript 语法,但对于 APIs 来说却并非如此。 414 | 415 | 比方说,下列含有箭头函数的需要编译的代码: 416 | 417 | ```js 418 | function addAll() { 419 | return Array.from(arguments).reduce((a, b) => a + b); 420 | } 421 | ``` 422 | 423 | 最终会变成这样: 424 | 425 | ```js 426 | function addAll() { 427 | return Array.from(arguments).reduce(function(a, b) { 428 | return a + b; 429 | }); 430 | } 431 | ``` 432 | 433 | 然而,它依然无法随处可用因为不是所有的 JavaScript 环境都支持 `Array.from`。 434 | 435 | Uncaught TypeError: Array.from is not a function 436 | 437 | 438 | 为了解决这个问题,我们使用一种叫做 [Polyfill(代码填充,也可译作兼容性补丁)](https://remysharp.com/2010/10/08/what-is-a-polyfill) 的技术。 简单地说,polyfill 即是在当前运行环境中用来复制(意指模拟性的复制,而不是拷贝)尚不存在的原生 api 的代码。 能让你提前使用还不可用的 APIs,`Array.from` 就是一个例子。 439 | 440 | Babel 用了优秀的 [core-js](https://github.com/zloirock/core-js) 用作 polyfill,并且还有定制化的 [regenerator](https://github.com/facebook/regenerator) 来让 generators(生成器)和 async functions(异步函数)正常工作。 441 | 442 | 要使用 Babel polyfill,首先用 npm 安装它: 443 | 444 | ```sh 445 | $ npm install --save babel-polyfill 446 | ``` 447 | 448 | 然后只需要在文件顶部导入 polyfill 就可以了: 449 | 450 | ```js 451 | import "babel-polyfill"; 452 | ``` 453 | 454 | ## `babel-runtime` 455 | 456 | 为了实现 ECMAScript 规范的细节,Babel 会使用“助手”方法来保持生成代码的整洁。 457 | 458 | 由于这些助手方法可能会特别长并且会被添加到每一个文件的顶部,因此你可以把它们统一移动到一个单一的“运行时(runtime)”中去。 459 | 460 | 通过安装 `babel-plugin-transform-runtime` 和 `babel-runtime` 来开始。 461 | 462 | ```sh 463 | $ npm install --save-dev babel-plugin-transform-runtime 464 | $ npm install --save babel-runtime 465 | ``` 466 | 467 | 然后更新 `.babelrc`: 468 | 469 | ```diff 470 | { 471 | "plugins": [ 472 | + "transform-runtime", 473 | "transform-es2015-classes" 474 | ] 475 | } 476 | ``` 477 | 478 | 现在,Babel 会把这样的代码: 479 | 480 | ```js 481 | class Foo { 482 | method() {} 483 | } 484 | ``` 485 | 486 | 编译成: 487 | 488 | ```js 489 | import _classCallCheck from "babel-runtime/helpers/classCallCheck"; 490 | import _createClass from "babel-runtime/helpers/createClass"; 491 | 492 | let Foo = function () { 493 | function Foo() { 494 | _classCallCheck(this, Foo); 495 | } 496 | 497 | _createClass(Foo, [{ 498 | key: "method", 499 | value: function method() {} 500 | }]); 501 | 502 | return Foo; 503 | }(); 504 | ``` 505 | 506 | 这样就不需要把 `_classCallCheck` 和 `_createClass` 这两个助手方法放进每一个需要的文件里去了。 507 | 508 | * * * 509 | 510 | # 配置 Babel(进阶) 511 | 512 | 大多数人使用 Babel 的内建预设就足够了,不过 Babel 提供了更多更细粒度的能力。 513 | 514 | ## 手动指定插件 515 | 516 | Babel 预设就是一些预先配置好的插件的集合,如果你想要做一些不一样的事情你会手动去设定插件,这和使用预设几乎完全相同。 517 | 518 | 首先安装插件: 519 | 520 | ```sh 521 | $ npm install --save-dev babel-plugin-transform-es2015-classes 522 | ``` 523 | 524 | 然后往 `.babelrc` 文件添加 `plugins` 字段。. 525 | 526 | ```diff 527 | { 528 | + "plugins": [ 529 | + "transform-es2015-classes" 530 | + ] 531 | } 532 | ``` 533 | 534 | 这能让你对正在使用的转换器进行更细致的控制。 535 | 536 | 完整的官方插件列表请见 [Babel 插件页面](http://babeljs.io/docs/plugins/)。. 537 | 538 | 同时也别忘了看看[由社区构建的其他插件](https://www.npmjs.com/search?q=babel-plugin)。 如果你想学习如何编写自己的插件可以阅读 [Babel 插件手册](plugin-handbook.md)。. 539 | 540 | ## 插件选项 541 | 542 | 很多插件也有选项用于配置他们自身的行为。 例如,很多转换器都有“宽松”模式,通过放弃一些标准中的行为来生成更简化且性能更好的代码。 543 | 544 | 要为插件添加选项,只需要做出以下更改: 545 | 546 | ```diff 547 | { 548 | "plugins": [ 549 | - "transform-es2015-classes" 550 | + ["transform-es2015-classes", { "loose": true }] 551 | ] 552 | } 553 | ``` 554 | 555 | > 接下来几周内我会更新插件文档来详细介绍每一个选项。[关注我以获知更新](https://twitter.com/thejameskyle)。. 556 | 557 | ## 基于环境自定义 Babel 558 | 559 | Babel 插件解决许多不同的问题。 其中大多数是开发工具,可以帮助你调试代码或是与工具集成。 也有大量的插件用于在生产环境中优化你的代码。 560 | 561 | 因此,想要基于环境来配置 Babel 是很常见的。你可以轻松的使用 `.babelrc` 文件来达成目的。 562 | 563 | ```diff 564 | { 565 | "presets": ["es2015"], 566 | "plugins": [], 567 | + "env": { 568 | + "development": { 569 | + "plugins": [...] 570 | + }, 571 | + "production": { 572 | + "plugins": [...] 573 | + } 574 | } 575 | } 576 | ``` 577 | 578 | Babel 将根据当前环境来开启 `env` 下的配置。 579 | 580 | 当前环境可以使用 `process.env.BABEL_ENV` 来获得。 如果 `BABEL_ENV` 不可用,将会替换成 `NODE_ENV`,并且如果后者也没有设置,那么缺省值是`"development"`。. 581 | 582 | **Unix** 583 | 584 | ```sh 585 | $ BABEL_ENV=production [COMMAND] 586 | $ NODE_ENV=production [COMMAND] 587 | ``` 588 | 589 | **Windows** 590 | 591 | ```sh 592 | $ SET BABEL_ENV=production 593 | $ [COMMAND] 594 | ``` 595 | 596 | > **注意:**`[COMMAND]` 指的是任意一个用来运行 Babel 的命令(如:`babel`,`babel-node`,或是 `node`,如果你使用了 register 钩子的话)。 597 | > 598 | > **提示:**如果你想要让命令能够跨 unix 和 windows 平台运行的话,可以使用 [`cross-env`](https://www.npmjs.com/package/cross-env)。. 599 | 600 | ## 制作你自己的预设(preset) 601 | 602 | 手动指定插件?插件选项?环境特定设置?所有这些配置都会在你的项目里产生大量的重复工作。 603 | 604 | 为此,我们鼓励社区创建自己的预设。 这可能是一个针对特定 [node 版本](https://github.com/leebenson/babel-preset-node5)的预设,或是适用于你[整个](https://github.com/cloudflare/babel-preset-cf)[公司](https://github.com/airbnb/babel-preset-airbnb)的预设。. 605 | 606 | 创建预设非常容易。比方说你这样一个 `.babelrc` 文件: 607 | 608 | ```js 609 | { 610 | "presets": [ 611 | "es2015", 612 | "react" 613 | ], 614 | "plugins": [ 615 | "transform-flow-strip-types" 616 | ] 617 | } 618 | ``` 619 | 620 | 你要做的就是依循命名约定 `babel-preset-*` 来创建一个新项目(请务必对这个命名约定保持责任心,也就是说不要滥用这个命名空间),然后创建两个文件。 621 | 622 | 首先,创建一个 `package.json`,包括针对预设所必要的 `dependencies`。 623 | 624 | ```js 625 | { 626 | "name": "babel-preset-my-awesome-preset", 627 | "version": "1.0.0", 628 | "author": "James Kyle ", 629 | "dependencies": { 630 | "babel-preset-es2015": "^6.3.13", 631 | "babel-preset-react": "^6.3.13", 632 | "babel-plugin-transform-flow-strip-types": "^6.3.15" 633 | } 634 | } 635 | ``` 636 | 637 | 然后创建 `index.js` 文件用于导出 `.babelrc` 的内容,使用对应的 `require` 调用来替换 plugins/presets 字符串。 638 | 639 | ```js 640 | module.exports = { 641 | presets: [ 642 | require("babel-preset-es2015"), 643 | require("babel-preset-react") 644 | ], 645 | plugins: [ 646 | require("babel-plugin-transform-flow-strip-types") 647 | ] 648 | }; 649 | ``` 650 | 651 | 然后只需要发布到 npm 于是你就可以像其它预设一样来使用你的预设了。 652 | 653 | * * * 654 | 655 | # Babel 和其他工具 656 | 657 | 一旦你掌握的窍门,安装 Babel 还是十分简明的,不过和其他工具搭配在一起就会变得困难多了。 不过我们一直在与其他项目密切合作以确保这种体验尽可能简单。 658 | 659 | ## 静态分析工具 660 | 661 | 新标准为语言带来了许多新的语法,静态分析工具正在将此利用起来。 662 | 663 | ### 语法检查(Linting) 664 | 665 | [ESLint](http://eslint.org) 是最流行的语法检查工具之一,因此我们维护了一个官方的 [`babel-eslint`](https://github.com/babel/babel-eslint) 整合软件包。 666 | 667 | 首先安装 `eslint` 和 `babel-eslint`。. 668 | 669 | ```sh 670 | $ npm install --save-dev eslint babel-eslint 671 | ``` 672 | 673 | 然后创建或使用项目现有的 `.eslintrc` 文件并设置 `parser` 为 `babel-eslint`。. 674 | 675 | ```diff 676 | { 677 | + "parser": "babel-eslint", 678 | "rules": { 679 | ... 680 | } 681 | } 682 | ``` 683 | 684 | 现在添加一个 `lint` 任务到 npm 的 `package.json` 脚本中: 685 | 686 | ```diff 687 | { 688 | "name": "my-module", 689 | "scripts": { 690 | + "lint": "eslint my-files.js" 691 | }, 692 | "devDependencies": { 693 | "babel-eslint": "...", 694 | "eslint": "..." 695 | } 696 | } 697 | ``` 698 | 699 | 接着只需要运行这个任务就一切就绪了。 700 | 701 | ```sh 702 | $ npm run lint 703 | ``` 704 | 705 | 详细信息请咨询 [`babel-eslint`](https://github.com/babel/babel-eslint) 或者 [`eslint`](http://eslint.org) 的文档。 706 | 707 | ### 代码风格 708 | 709 | > JSCS已经和ESLint合并,所以请查看ESLint的代码风格。 710 | 711 | JSCS 是一个极受欢迎的工具,在语法检查的基础上更进一步检查代码自身的风格。 Babel 和 JSCS 项目的核心维护者之一([@hzoo](https://github.com/hzoo))维护着 JSCS 的官方集成。 712 | 713 | 更妙的是,JSCS 自己通过 `--esnext` 选项实现了这种集成,于是和 Babel 的集成就简化成了直接在命令行运行: 714 | 715 | $ jscs . --esnext 716 | 717 | 718 | 或者在 `.jscsrc` 文件里添加 `esnext` 选项。 719 | 720 | ```diff 721 | { 722 | "preset": "airbnb", 723 | + "esnext": true 724 | } 725 | ``` 726 | 727 | 详细信息请咨询 [`babel-jscs`](https://github.com/jscs-dev/babel-jscs) 或是 [`jscs`](http://jscs.info) 的文档。 728 | 729 | 734 | 735 | ### 文档 736 | 737 | 使用 Babel,ES2015,还有 Flow 你可以对你的代码进行大量的推断。使用 [documentation.js](http://documentation.js.org) 可以非常简便地生成详细的 API 文档。 738 | 739 | Documentation.js 使用 Babel 来支持所有最新的语法,包括用于在你的代码中声明类型所用的 Flow 注解在内, 740 | 741 | ## 框架 742 | 743 | 所有主流的 JavaScript 框架都正在努力调整他们的 APIs 向这门语言的未来看齐。有鉴于此,配套工具方面已经做出了大量的工作。 744 | 745 | 除了使用 Babel 以外,框架更有条件去扩展 Babel 来帮助他们提升用户体验。 746 | 747 | ### React 748 | 749 | React 已经大幅改变了他们的 API 以适应 ES2015 的类语法([此处了解更新的 API](https://babeljs.io/blog/2015/06/07/react-on-es6-plus))。 特别是 React 现在依赖 Babel 编译它的 JSX 语法且弃用了它原有的自定义工具。 你可以按照[上述说明](#babel-preset-react)安装 `babel-preset-react` 包来开始。. 750 | 751 | React 社区采用 Babel 并围绕它来运行,现在社区已经创建了[大量的转换器(transforms)](https://www.npmjs.com/search?q=babel-plugin+react)。. 752 | 753 | 最令人瞩目的是 [`babel-plugin-react-transform`](https://github.com/gaearon/babel-plugin-react-transform) 插件,它集成了大量 [React 专用转换器](https://github.com/gaearon/babel-plugin-react-transform#transforms)可以启用诸如 *热模块重载*等其他调试工具。 754 | 755 | 760 | 761 | ## 文本编辑器和 IDEs(集成开发环境) 762 | 763 | 通过 Babel 引入 ES2015,JSX,和流式语法固然是大有裨益,可如果你的文本编辑不支持那可就糟糕透了。 因此,别忘了为你的文本编辑器或是 IDE 安装 Babel 插件。 764 | 765 | * [Sublime Text](https://github.com/babel/babel-sublime) 766 | * [Atom](https://atom.io/packages/language-babel) 767 | * [Vim](https://github.com/jbgutierrez/vim-babel) 768 | * [WebStorm](https://babeljs.io/docs/setup/#webstorm) 769 | 770 | 775 | 776 | * * * 777 | 778 | # Babel 支持 779 | 780 | Babel 的社区非常庞大并且增长速度很快,伴随着我们成长的同时我们希望保证人们总能获取他们需要的所有资源。 所以我们提供了数种途径来提供支持。 781 | 782 | 谨记在所有的这些沟通渠道里我们都共同遵守一套[行为准则](https://github.com/babel/babel/blob/master/CODE_OF_CONDUCT.md)。 破坏准则的行为会被处理。 所以请阅读它并在与他人互动时注意自己的行为。 783 | 784 | 同时我们也在寻求发展一个自我支持式的社区,为那些始终热诚奉献的人们。 如果别人问的问题你恰好知道答案,请不吝花费几分钟帮帮他们。 在此过程中也请尽力保持友善与相互理解。 785 | 786 | ## Babel 论坛 787 | 788 | [Discourse](http://www.discourse.org) 免费为我们提供了一个托管版本的论坛(我们爱死他们了!)。 如果你是个论坛控请不要错过 [discuss.babeljs.io](https://discuss.babeljs.io)。. 789 | 790 | ## Babel 聊天 791 | 792 | 无人不爱 [Slack](https://slack.com)。如果你正在寻求来自社区的即时支持,那就来 [slack.babeljs.io](https://slack.babeljs.io) 和我们聊天吧。. 793 | 794 | 799 | 800 | ## Babel 问题 801 | 802 | Babel使用[Github](http://github.com)提供的问题跟踪器。. 803 | 804 | 您可以在[Github](https://github.com/babel/babel/issues)上看到所有的开放和封闭的问题. 805 | 806 | 如果你想要打开一个新的问题: 807 | 808 | * [先搜搜看有没有现存的类似问题](https://github.com/babel/babel/issues) 809 | * 创建一个新的错误报告 或请求新功能 810 | 811 | ### 创建漂亮的 Babel 错误报告 812 | 813 | Babel 的问题有时候很难远程调试,所以我们希望能获取尽可能详细的信息来帮助我们解决问题。 花点时间去撰写一份好的错误报告会让你的问题更快得到解决。 814 | 815 | 首先,尝试隔离问题。 并非设置过程的每一步都是导致问题的原因。 如果你的问题是一段输入代码,试着尽可能把与问题不相关的代码都删除掉。 816 | 817 | > [WIP] 818 | 819 | * * * 820 | 821 | > ***在 Twitter 上关注 [@thejameskyle](https://twitter.com/thejameskyle),第一时间获取更新。*** -------------------------------------------------------------------------------- /translations/ko/user-handbook.md: -------------------------------------------------------------------------------- 1 | # Babel User Handbook 2 | 3 | 이 문서는 모든 [Babel](https://babeljs.io)과 관련된 도구를 사용하는 방법에 대해 설명합니다. 4 | 5 | [![cc-by-4.0](https://licensebuttons.net/l/by/4.0/80x15.png)](http://creativecommons.org/licenses/by/4.0/) 6 | 7 | 이 핸드북은 다른 언어로도 볼 수 있습니다. 전체 목록은 [README](/README.md)를 참고하세요. 8 | 9 | # 목차 10 | 11 | * [소개](#toc-introduction) 12 | * [Babel 설정하기](#toc-setting-up-babel) 13 | * [`babel-cli`](#toc-babel-cli) 14 | * [프로젝트 내에서 Babel CLI 실행하기](#toc-running-babel-cli-from-within-a-project) 15 | * [`babel-register`](#toc-babel-register) 16 | * [`babel-node`](#toc-babel-node) 17 | * [`babel-core`](#toc-babel-core) 18 | * [Babel 컨픽 작성하기](#toc-configuring-babel) 19 | * [`.babelrc`](#toc-babelrc) 20 | * [`babel-preset-es2015`](#toc-babel-preset-es2015) 21 | * [`babel-preset-react`](#toc-babel-preset-react) 22 | * [`babel-preset-stage-x`](#toc-babel-preset-stage-x) 23 | * [Babel로 생성된 코드 실행하기](#toc-executing-babel-generated-code) 24 | * [`babel-polyfill`](#toc-babel-polyfill) 25 | * [`babel-runtime`](#toc-babel-runtime) 26 | * [Babel 컨픽 작성하기 (고급)](#toc-configuring-babel-advanced) 27 | * [수동으로 플러그인 지정하기](#toc-manually-specifying-plugins) 28 | * [플러그인 옵션](#toc-plugin-options) 29 | * [환경에 따른 Babel 커스터마이징](#toc-customizing-babel-based-on-environment) 30 | * [나만의 프리셋 만들기](#toc-making-your-own-preset) 31 | * [Babel과 기타 도구들](#toc-babel-and-other-tools) 32 | * [정적 분석 도구](#toc-static-analysis-tools) 33 | * [코드 검사기 (Linter)](#toc-linting) 34 | * [코드 스타일](#toc-code-style) 35 | * [문서](#toc-documentation) 36 | * [프레임워크](#toc-frameworks) 37 | * [React](#toc-react) 38 | * [텍스트 편집기와 IDE](#toc-text-editors-and-ides) 39 | * [Babel 지원](#toc-babel-support) 40 | * [Babel 포럼](#toc-babel-forum) 41 | * [Babel 채팅](#toc-babel-chat) 42 | * [Babel 이슈](#toc-babel-issues) 43 | * [멋진 Babel 버그 보고 생성](#toc-creating-an-awesome-babel-bug-report) 44 | 45 | # 소개 46 | 47 | Babel은 JavaScript를 위한 일반적인 다중 목적 컴파일러입니다. Babel은 다음 세대의 JavaScript를 사용할 수 있도록 해주고 (만들 수 있도록), 그 뿐만 아니라 다음 세대의 JavaScript 유용한 유틸리티를 제공합니다. 48 | 49 | JavaScript는 언어로써 새로운 스팩과 제안과 새로운 기능들이 언제나 나오며 끊임없이 발전하고 있습니다. Babel을 사용하면 언어적 기능이 본격적으로 모든 곳에서 사용되기 이전에 모든 기능을 미리 사용할 수 있습니다. 50 | 51 | Babel은 최신 표준으로 작성된 JavaScript 코드를 현재 어디서나 동작하는 코드로 컴파일합니다. 이 과정은 source-to-source 컴파일이라고도 부르고 트랜스파일이라고도 부릅니다. 52 | 53 | 예를 들어, Babel은 ES2015의 새로운 화살표 함수 문법을 변환할 수 있습니다: 54 | 55 | ```js 56 | const square = n => n * n; 57 | ``` 58 | 59 | 이를 다음과 같이 변환합니다: 60 | 61 | ```js 62 | const square = function square(n) { 63 | return n * n; 64 | }; 65 | ``` 66 | 67 | 하지만 Babel은 React의 JSX 문법이나 정적 타입 검사를 위한 Flow 문법 지원 같은 문법 확장도 지원하므로 위에서 본 것보다 더 많은 일을 할 수 있습니다. 68 | 69 | 더 나아가 Babel에서 모든 것은 단순한 플러그인이고 원한다면 언제든지 Babel의 모든 기능을 사용해서 자신만의 플러그인을 만들 수 있습니다. 70 | 71 | *여기서 더 나아가* Babel은 차세대 JavaScript 도구를 만드는데 사용할 수 있는 다수의 핵심 모듈로 모듈화되어 있습니다. 72 | 73 | 많은 사람들 하듯이 갑자기 등장한 Babel의 생태계는 아주 크고 매우 다양합니다. 이 핸드북에서 Babel의 내장 도구들이 동작하는 원리와 커뮤니티에서 만든 유용한 내용을 다룰 것입니다. 74 | 75 | > ***향후 업데이트에 대한 내용은 Twitter의 [@thejameskyle](https://twitter.com/thejameskyle)를 팔로우하세요.*** 76 | 77 | * * * 78 | 79 | # Babel 설정하기 80 | 81 | JavaScript 커뮤니티가 다양한 빌드도구, 프레임워크, 플랫폼 등을 가지므로 Babel은 주요 도구를 공식적으로 통합하고 있습니다. Gulp에서 Browserify 까지, Ember에서 Meteor까지 공식적인 통합이 있을 것 같은 모든 것을 설정해서 사용할 수 있습니다. 82 | 83 | 이 핸드북의 목적에 따라 Babel을 구성하는 내장된 방법을 설명하고 있지만 다른 통합에 대해서는 인터렉티브한 [설정 페이지](http://babeljs.io/docs/setup)를 사용할 수도 있습니다. 84 | 85 | > **Note:** 이 가이드에서는 `node`와 `npm`같은 커맨드라인 도구를 사용합니다. 더 진행하기 전에 이러한 도구에 익숙해 져야 합니다. 86 | 87 | ## `babel-cli` 88 | 89 | Babel의 CLI는 커맨드라인에서 Babel로 파일을 컴파일하는 간단한 방법입니다. 90 | 91 | 일단 기본을 배우기 위해 전역으로 설치해 보겠습니다. 92 | 93 | ```sh 94 | $ npm install --global babel-cli 95 | ``` 96 | 97 | 첫 파일을 다음과 같이 컴파일할 수 있습니다. 98 | 99 | ```sh 100 | $ babel my-file.js 101 | ``` 102 | 103 | 터미널에 컴파일된 결과가 바로 나타납니다. 컴파일된 결과를 파일에 쓰려면 `--out-file`나 `-o`을 지정해야 합니다.. 104 | 105 | ```sh 106 | $ babel example.js --out-file compiled.js 107 | # 또는 108 | $ babel example.js -o compiled.js 109 | ``` 110 | 111 | 디렉터리 전체를 새로운 디렉터리로 컴파일하고 싶다면 `--out-dir`나 `-d`를 사용합니다.. 112 | 113 | ```sh 114 | $ babel src --out-dir lib 115 | # 또는 116 | $ babel src -d lib 117 | ``` 118 | 119 | ### 프로젝트 내에서 Babel CLI 실행하기 120 | 121 | 자신의 머신에 Babel CLI를 전역으로 *설치할 수도 있지만* 프로젝트 **내부에** Babel을 설치하는 것이 훨씬 더 좋습니다. 122 | 123 | 내부에 설치하는 이유가 두 가지 있습니다. 124 | 125 | 1. 같은 머신에서 다른 프로젝트는 다른 버전의 Babel을 사용할 수 있으므로 한번에 하나씩 업데이트 할 수 있습니다. 126 | 2. 이는 작업하는 환경에 암묵적인 의존성을 갖지 않는다는 의미입니다. 프로젝트를 이식하고 구성하기 쉽게 만드세요. 127 | 128 | 다음 명령어로 Babel CLI를 프로젝트 내부에 설치할 수 있습니다. 129 | 130 | ```sh 131 | $ npm install --save-dev babel-cli 132 | ``` 133 | 134 | > **참고:** 전역에서 Babel을 실행하는 것은 좋지 않은 생각이므로 다음 명령으로 전역에 설치된 Babel을 지울 수 있습니다: 135 | > 136 | > ```sh 137 | $ npm uninstall --global babel-cli 138 | ``` 139 | 140 | 설치가 끝나면, `package.json`이 다음과 같이 표시되어야 합니다: 141 | 142 | ```json 143 | { 144 | "name": "my-project", 145 | "version": "1.0.0", 146 | "devDependencies": { 147 | "babel-cli": "^6.0.0" 148 | } 149 | } 150 | ``` 151 | 152 | 이제 CLI에서 Babel을 직접적으로 사용하는 대신, **npm scripts**를 추가하여 로컬 버전의 Babel을 사용하도록 명령어를 추가합니다. 153 | 154 | 간단히 `package.json`에 `"scripts"` 필드를 추가한 후 `build` 명령어와 같이 Babel 명령어를 추가하세요. 155 | 156 | ```diff 157 | { 158 | "name": "my-project", 159 | "version": "1.0.0", 160 | + "scripts": { 161 | + "build": "babel src -d lib" 162 | + }, 163 | "devDependencies": { 164 | "babel-cli": "^6.0.0" 165 | } 166 | } 167 | ``` 168 | 169 | 이제 터미널에서 다음을 실행할 수 있습니다: 170 | 171 | ```js 172 | npm run build 173 | ``` 174 | 175 | 이 명령어는 이전과 같이 Babel을 실행하지만, 로컬에 설치된 Babel을 사용합니다. 176 | 177 | ## `babel-register` 178 | 179 | Babel을 실행하는 또 다른 방법의 하나는 `babel-register`를 사용하는 것입니다. 이 방법을 이용하면 파일을 require하는 것만으로도 Babel을 실행할 수 있어 더 간단하게 설정에 통합할 수 있을 것입니다. 180 | 181 | 이는 프로덕션에서 사용할 목적이라는 의미는 아닙니다. 이 방법으로 컴파일되는 코드를 배포하는 것은 좋지 않은 방법입니다. 배포하기 전에 미리 컴파일하는 것이 훨씬 나은 방법입니다. 하지만 빌드 스크립트나 로컬에서 실행하는 다른 작업에서는 아주 잘 동작합니다. 182 | 183 | 먼저 프로젝트에 `index.js`을 생성해 보겠습니다. 184 | 185 | ```js 186 | console.log("Hello world!"); 187 | ``` 188 | 189 | 이 파일을 `node index.js`로 실행한다면 Babel로 컴파일되지 않을 것이므로 대신 `babel-register`를 설정해 보겠습니다.. 190 | 191 | 먼저 `babel-register`를 설치하세요. 192 | 193 | ```sh 194 | $ npm install --save-dev babel-register 195 | ``` 196 | 197 | 그다음 프로젝트에 `register.js` 파일을 생성하고 다음 코드를 작성하세요. 198 | 199 | ```js 200 | require("babel-register"); 201 | require("./index.js"); 202 | ``` 203 | 204 | 이 코드는 Node의 모듈 시스템에 Babel을 *등록하고* `require`하는 모든 파일을 컴파일합니다. 205 | 206 | 이제 `node index.js`를 실행하는 대신 `register.js`를 사용할 수 있습니다. 207 | 208 | ```sh 209 | $ node register.js 210 | ``` 211 | 212 | > **Note:** Babel이 코드를 컴파일하기 전에 node가 파일을 실행하므로 컴파일하려는 파일에서 Babel을 등록할 수는 없습니다. 213 | > 214 | > ```js 215 | require("babel-register"); 216 | // 컴파일되지 않음: 217 | console.log("Hello world!"); 218 | ``` 219 | 220 | ## `babel-node` 221 | 222 | `node` CLI로 코드를 실행한다면 `node` CLI의 대체물인 `babel-node` CLI를 사용하는 것이 Babel을 통합하는 가장 쉬운 방법입니다. 223 | 224 | 이는 프로덕션에서 사용할 목적이라는 의미는 아닙니다. 이 방법으로 컴파일되는 코드를 배포하는 것은 좋지 않은 방법입니다. 배포하기 전에 미리 컴파일하는 것이 훨씬 나은 방법입니다. 하지만 빌드 스크립트나 로컬에서 실행하는 다른 작업에서는 아주 잘 동작합니다. 225 | 226 | 일단 `babel-cli`가 설치되었는지 확인합니다. 227 | 228 | ```sh 229 | $ npm install --save-dev babel-cli 230 | ``` 231 | 232 | > **Note:** 왜 이것을 로컬에 설치하는지 궁금하다면, [프로젝트에서 Babel CLI 실행하기](#toc-running-babel-cli-from-within-a-project) 부분을 읽어 보세요. 233 | 234 | 그 다음 `node`를 사용하는 대신 `babel-node`를 사용하세요.. 235 | 236 | npm `scripts`를 사용한다면 다음과 같이 설정할 수 있습니다. 237 | 238 | ```diff 239 | { 240 | "scripts": { 241 | - "script-name": "node script.js" 242 | + "script-name": "babel-node script.js" 243 | } 244 | } 245 | ``` 246 | 247 | 아니면 `babel-node`의 경로를 적어주어야 합니다. 248 | 249 | ```diff 250 | - node script.js 251 | + ./node_modules/.bin/babel-node script.js 252 | ``` 253 | 254 | > Tip: [`npm-run`](https://www.npmjs.com/package/npm-run)을 사용할 수도 있습니다.. 255 | 256 | ## `babel-core` 257 | 258 | 만약 어떠한 이유로 Babel을 프로그래밍 방식으로 사용해야 하는 경우, `babel-core` 패키지 자체를 사용할 수도 있습니다. 259 | 260 | 먼저 `babel-core`를 설치합니다. 261 | 262 | ```sh 263 | $ npm install babel-core 264 | ``` 265 | 266 | ```js 267 | var babel = require("babel-core"); 268 | ``` 269 | 270 | 만약 JavaScript 문자열이 있는 경우 `babel.transform`를 통해 바로 컴파일 할 수 있습니다.. 271 | 272 | ```js 273 | babel.transform("code();", options); 274 | // => { code, map, ast } 275 | ``` 276 | 277 | 만약 파일로 작업하고 있다면 비동기 api와 함께 사용할 수 있습니다: 278 | 279 | ```js 280 | babel.transformFile("filename.js", options, function(err, result) { 281 | result; // => { code, map, ast } 282 | }); 283 | ``` 284 | 285 | 또는 동기 api를 사용할 수도 있습니다: 286 | 287 | ```js 288 | babel.transformFileSync("filename.js", options); 289 | // => { code, map, ast } 290 | ``` 291 | 292 | 만약 어떠한 이유로 이미 Babel AST를 가지고 있다면 AST를 통해 직접 변환할 수 있습니다. 293 | 294 | ```js 295 | babel.transformFromAst(ast, code, options); 296 | // => { code, map, ast } 297 | ``` 298 | 299 | For all of the above methods, `options` refers to https://babeljs.io/docs/usage/api/#options. 300 | 301 | * * * 302 | 303 | # Babel 설정 파일 작성하기 304 | 305 | 아마 Babel을 실행했을 때 JavaScript 파일들을 다른 경로로 복사하는 것 말고는 아무 일도 하지 않는다는 것을 눈치챘을 겁니다. 306 | 307 | 이는 아직 Babel에게 할 일을 아무것도 주지 않았기 때문입니다. 308 | 309 | > Babel이 범용 컴파일러가 된 이후부터 무수히 많은 용도로 쓰이게 되었으나 기본적으론 아무 일도 하지 않습니다. 따라서 명시적으로 Babel에게 할 일을 알려주어야 합니다. 310 | 311 | **플러그인** 또는 **프리셋** (플러그인 모음)을 설치함으로써 Babel에게 지시를 내릴 수 있습니다. 312 | 313 | ## `.babelrc` 314 | 315 | Babel에게 무엇을 해야 하는지 지시하기 전에, 파일을 하나 만들어야 합니다. 작업하기 전에 가장 먼저 할 것은 프로젝트의 루트에 `.babelrc` 파일을 만드는 것입니다. 다음과 같이 작성합니다: 316 | 317 | ```js 318 | { 319 | "presets": [], 320 | "plugins": [] 321 | } 322 | ``` 323 | 324 | 이 파일은 Babel이 어떤 작업을 해야 할 지 구성합니다. 325 | 326 | > **참고:** 또한 `.babelrc`에서 Babel에 옵션을 전달할 수도 있으며 가장 좋은 방법입니다. 327 | 328 | ## `babel-preset-es2015` 329 | 330 | 이제 Babel에게 ES2015 (ES6으로 알려진 새로운 버전의 JavaScript 표준)를 ES5 (현대 대부분의 환경이 실행할 수 있는 JavaScript 버전)로 컴파일하도록 지시해봅시다. 331 | 332 | 위 커맨드는 "es2015" Babel 프리셋을 설치할 것입니다: 333 | 334 | ```sh 335 | $ npm install --save-dev babel-preset-es2015 336 | ``` 337 | 338 | 다음은 `.babelrc`가 프리셋을 포함하도록 수정합니다. 339 | 340 | ```diff 341 | { 342 | "presets": [ 343 | + "es2015" 344 | ], 345 | "plugins": [] 346 | } 347 | ``` 348 | 349 | ## `babel-preset-react` 350 | 351 | React를 설정하는 것은 매우 쉽습니다. 그저 프리셋을 설치하고: 352 | 353 | ```sh 354 | $ npm install --save-dev babel-preset-react 355 | ``` 356 | 357 | `.babelrc` 파일에 프리셋을 추가합니다: 358 | 359 | ```diff 360 | { 361 | "presets": [ 362 | "es2015", 363 | + "react" 364 | ], 365 | "plugins": [] 366 | } 367 | ``` 368 | 369 | ## `babel-preset-stage-x` 370 | 371 | 자바스크립트는 표준으로 만들기 위한 몇 가지 제안 사항을 가지고 있고 TC39의 진행 상황에 따라 표준이 제정됩니다. (ECMAScript 표준 기술 위원회) 372 | 373 | 이 과정은 5 스테이지 (0-4) 로 진행됩니다. 제안은 어느 정도의 호응과 함께 표준이 되어야 한다고 판단되면 스테이지에 따라 표준화 작업을 진행합니다. 최종 표준으로 받아들여질 제안은 stage 4에 위치됩니다. 374 | 375 | Babel에선 다음 4가지 프리셋으로 번들되어 있습니다: 376 | 377 | * `babel-preset-stage-0` 378 | * `babel-preset-stage-1` 379 | * `babel-preset-stage-2` 380 | * `babel-preset-stage-3` 381 | 382 | > stage-4 프리셋은 단순히 `es2015`이며 따로 프리셋이 존재하진 않습니다. 383 | 384 | 각 프리셋들은 이후의 프리셋을 자동으로 포함합니다. 즉, `babel-preset-stage-1`은 `babel-preset-stage-2`를 포함하며 다시 이 프리셋은 `babel-preset-stage-3`를 포함합니다. 385 | 386 | 관심이 있다면 단순히 다음과 같이 원하는 스테이지를 설치합니다: 387 | 388 | ```sh 389 | $ npm install --save-dev babel-preset-stage-2 390 | ``` 391 | 392 | 그런 다음 `.babelrc` 설정에 추가할 수 있습니다. 393 | 394 | ```diff 395 | { 396 | "presets": [ 397 | "es2015", 398 | "react", 399 | + "stage-2" 400 | ], 401 | "plugins": [] 402 | } 403 | ``` 404 | 405 | * * * 406 | 407 | # Babel로 생성된 코드 실행하기 408 | 409 | 그래서 일단 Babel로 코드를 컴파일 했습니다, 하지만 아직 끝나지 않았습니다. 410 | 411 | ## `babel-polyfill` 412 | 413 | 거의 모든 미래적인 JavaScript 문법은 Babel로 컴파일할 수 있습니다. 하지만 API는 그렇지 않습니다. 414 | 415 | 예를 들어, 다음 코드는 화살표 함수를 포함하고 있고 컴파일되어야 합니다: 416 | 417 | ```js 418 | function addAll() { 419 | return Array.from(arguments).reduce((a, b) => a + b); 420 | } 421 | ``` 422 | 423 | 위 코드는 다음과 같이 변환됩니다: 424 | 425 | ```js 426 | function addAll() { 427 | return Array.from(arguments).reduce(function(a, b) { 428 | return a + b; 429 | }); 430 | } 431 | ``` 432 | 433 | 그러나, 모든 JavaScript 환경에 `Array.from`가 있지 않기 때문에 여전히 어디서나 작동하진 않을 것입니다. 434 | 435 | Uncaught TypeError: Array.from is not a function 436 | 437 | 438 | 이러한 문제는 [Polyfill](https://remysharp.com/2010/10/08/what-is-a-polyfill)을 사용함으로써 해결할 수 있습니다. 간단히 설명하자면, polyfill은 현재 런타임에 존재하지 않는 네이티브 API를 흉내내는 코드입니다. 이로써 `Array.from` 같은 API들을 환경의 지원에 상관없이 언제나 사용할 수 있습니다. 439 | 440 | Babel은 우수한 [core-js](https://github.com/zloirock/core-js)를 polyfill로 사용하고, 생성기와 async 함수가 작동할 수 있도록 약간 변경한 [regenerator](https://github.com/facebook/regenerator) 런타임을 사용합니다. 441 | 442 | Babel polyfill을 포함하려면, 먼저 npm으로 설치합니다: 443 | 444 | ```sh 445 | $ npm install --save babel-polyfill 446 | ``` 447 | 448 | 그리고 간단히 어떤 파일의 가장 상단에 다음 코드를 추가합니다: 449 | 450 | ```js 451 | import "babel-polyfill"; 452 | ``` 453 | 454 | ## `babel-runtime` 455 | 456 | ECMAScript 스팩의 상세 구현을 따르기 위함과 동시에 생성되는 코드를 깨끗하게 유지하기 위해, Babel은 "helper" 메서드를 사용할 것입니다. 457 | 458 | 이러한 헬퍼 코드는 상당히 길고 매 파일 위에 삽입되어야 하기 때문에, 필요하다면 단일 "runtime"으로 모든 헬퍼 코드를 옮길 수 있습니다. 459 | 460 | 먼저 `babel-plugin-transform-runtime`과 `babel-runtime`을 설치합니다: 461 | 462 | ```sh 463 | $ npm install --save-dev babel-plugin-transform-runtime 464 | $ npm install --save babel-runtime 465 | ``` 466 | 467 | 그리고 `.babelrc`를 수정하세요: 468 | 469 | ```diff 470 | { 471 | "plugins": [ 472 | + "transform-runtime", 473 | "transform-es2015-classes" 474 | ] 475 | } 476 | ``` 477 | 478 | 이제 Babel은 다음 코드를: 479 | 480 | ```js 481 | class Foo { 482 | method() {} 483 | } 484 | ``` 485 | 486 | 다음과 같이 컴파일할 것입니다: 487 | 488 | ```js 489 | import _classCallCheck from "babel-runtime/helpers/classCallCheck"; 490 | import _createClass from "babel-runtime/helpers/createClass"; 491 | 492 | let Foo = function () { 493 | function Foo() { 494 | _classCallCheck(this, Foo); 495 | } 496 | 497 | _createClass(Foo, [{ 498 | key: "method", 499 | value: function method() {} 500 | }]); 501 | 502 | return Foo; 503 | }(); 504 | ``` 505 | 506 | 필요할 때마다 매 파일에 `_classCallCheck`와 `_createClass` 헬퍼를 삽입하는 대신 위와 같이 런타임 헬퍼를 사용하는 것으로 변경됩니다. 507 | 508 | * * * 509 | 510 | # Babel 설정 파일 작성하기 (고급) 511 | 512 | 대부분의 사람들은 Babel과 빌트인 프리셋만을 사용합니다. 하지만 Babel은 더 세분화된 작업을 할 수 있습니다. 513 | 514 | ## 수동으로 플러그인 지정하기 515 | 516 | Babel 프리셋은 미리 구성된 플러그인들의 집합입니다. 만약 플러그인을 특정하여 다른 작업을 하고 싶다면, 프리셋과 거의 정확히 같은 방식으로 작동합니다. 517 | 518 | 먼저 플러그인을 설치합니다: 519 | 520 | ```sh 521 | $ npm install --save-dev babel-plugin-transform-es2015-classes 522 | ``` 523 | 524 | 그리고 `.babelrc`의 `plugins` 필드에 추가합니다. 525 | 526 | ```diff 527 | { 528 | + "plugins": [ 529 | + "transform-es2015-classes" 530 | + ] 531 | } 532 | ``` 533 | 534 | 이는 세분화된 트랜스폼을 통해 세밀한 작업을 할 수 있게 해줍니다. 535 | 536 | 전체 공식 플러그인 리스트는 [Babel Plugins 페이지](http://babeljs.io/docs/plugins/)에서 확인할 수 있습니다. 537 | 538 | 또한 이미 [커뮤니티에 의해 만들어진](https://www.npmjs.com/search?q=babel-plugin) 모든 플러그인을 사용할 수도 있습니다. 만약 자신만의 플러그인을 작성하는 방법을 배우고 싶다면 [Babel Plugin Handbook](plugin-handbook.md)을 읽으세요.. 539 | 540 | ## 플러그인 옵션 541 | 542 | 또한 많은 플러그인들이 다르게 동작 하도록 구성할 수 있는 옵션을 가지고 있습니다. 예를 들면, 많은 트랜스폼이 일부 스펙을 지키지 않는 대신 생성되는 코드의 성능을 개선하고 단순하게 만드는 "loose" 모드를 가지고 있습니다. 543 | 544 | 플러그인에 옵션을 추가하려면, 간단히 설정을 다음과 같이 변경하면 됩니다: 545 | 546 | ```diff 547 | { 548 | "plugins": [ 549 | - "transform-es2015-classes" 550 | + ["transform-es2015-classes", { "loose": true }] 551 | ] 552 | } 553 | ``` 554 | 555 | > 앞으로 몇 주 내로 모든 플러그인 옵션의 상세 사항을 포함하도록 플러그인 문서를 업데이트할 예정입니다. [업데이트 소식을 얻으려면 팔로우](https://twitter.com/thejameskyle). 556 | 557 | ## 환경에 따른 Babel 커스터마이징 558 | 559 | Babel 플러그인은 많은 다른 작업을 해결합니다. 대부분의 경우는 개발 툴이며 코드를 디버깅하거나 다른 툴과 통합할 수 있도록 도와줍니다. 또한 실제 프로덕션 코드를 위한 수 많은 최적화 플러그인도 많이 있습니다. 560 | 561 | 이러한 이유로 인해 Babel을 환경에 따라 구성을 변경하려 하는 것이 일반적입니다. `.babelrc`에서 쉽게 할 수 있습니다. 562 | 563 | ```diff 564 | { 565 | "presets": ["es2015"], 566 | "plugins": [], 567 | + "env": { 568 | + "development": { 569 | + "plugins": [...] 570 | + }, 571 | + "production": { 572 | + "plugins": [...] 573 | + } 574 | } 575 | } 576 | ``` 577 | 578 | Babel은 현재 환경에 따라 `env` 내에 정의된 구성을 활성화 할 것입니다. 579 | 580 | 현재 환경은 `process.env.BABEL_ENV` 변수를 사용합니다. `BABEL_ENV`를 사용할 수 없다면, `NODE_ENV`를 대신 사용합니다. 만약 둘 다 사용할 수 없다면 기본으로 `"development"`가 지정됩니다.. 581 | 582 | **Unix** 583 | 584 | ```sh 585 | $ BABEL_ENV=production [COMMAND] 586 | $ NODE_ENV=production [COMMAND] 587 | ``` 588 | 589 | **Windows** 590 | 591 | ```sh 592 | $ SET BABEL_ENV=production 593 | $ [COMMAND] 594 | ``` 595 | 596 | > **참고:** `[COMMAND]`는 Babel을 실행하기 위한 명령어입니다. (ie. `babel`, `babel-node`, 또는 register 훅을 사용할 경우 그냥 `node`) 597 | > 598 | > **Tip:** 만약 명령어가 unix와 windows 플랫폼에서 모두 작동하도록 하고 싶다면 [`cross-env`](https://www.npmjs.com/package/cross-env)를 사용하세요.. 599 | 600 | ## 나만의 프리셋 만들기 601 | 602 | 직접 플러그인과 플러그인 옵션, 환경에 따른 설정을 지정하는 경우 모든 설정 과정이 프로젝트마다 되풀이되는 것을 느낄 것입니다. 603 | 604 | 이러한 이유로, 우리는 커뮤니티가 용도에 맞는 프리셋을 직접 만드는 것을 권장합니다. 이는 실행하고 있는 [node 버전](https://github.com/leebenson/babel-preset-node5)에 대해 특정되거나 [전적](https://github.com/cloudflare/babel-preset-cf)으로 [회사](https://github.com/airbnb/babel-preset-airbnb)에 관련된 프리셋이 될 수 있습니다.. 605 | 606 | 프리셋을 만드는 것은 간단합니다. 다음과 같은 `.babelrc`를 프리셋으로 만드려면: 607 | 608 | ```js 609 | { 610 | "presets": [ 611 | "es2015", 612 | "react" 613 | ], 614 | "plugins": [ 615 | "transform-flow-strip-types" 616 | ] 617 | } 618 | ``` 619 | 620 | 프리셋을 만들기 위해 해야 할 일은 단지 새 프로젝트를 만들고 `babel-preset-*`과 같은 명명법을 따르는 것 입니다. (네임 스페이스를 만들었다면 꼭 책임을 지시기 바랍니다) 그리고 두 개의 파일을 생성합니다. 621 | 622 | 먼저, 새 `package.json` 파일을 만든 후 프리셋에서 요구하는 `종속성`들을 설치합니다. 623 | 624 | ```js 625 | { 626 | "name": "babel-preset-my-awesome-preset", 627 | "version": "1.0.0", 628 | "author": "James Kyle ", 629 | "dependencies": { 630 | "babel-preset-es2015": "^6.3.13", 631 | "babel-preset-react": "^6.3.13", 632 | "babel-plugin-transform-flow-strip-types": "^6.3.15" 633 | } 634 | } 635 | ``` 636 | 637 | 그리고 `index.js` 파일을 생성한 후 `.babelrc`의 내용을 export하도록 만들고 플러그인/프리셋 문자열을 `require` 호출로 바꿉니다. 638 | 639 | ```js 640 | module.exports = { 641 | presets: [ 642 | require("babel-preset-es2015"), 643 | require("babel-preset-react") 644 | ], 645 | plugins: [ 646 | require("babel-plugin-transform-flow-strip-types") 647 | ] 648 | }; 649 | ``` 650 | 651 | 그리고 간단히 npm에 배포하면 이 프리셋을 원하는 곳에 사용할 수 있습니다. 652 | 653 | * * * 654 | 655 | # Babel과 기타 도구들 656 | 657 | Babel은 설치 방법이 아주 직관적입니다. 하지만 다른 툴과 함께 사용하는 경우라면 설정하는 방법을 탐색하는 것이 어려울 수 있습니다. 그러나, 우리는 다른 프로젝트와의 운용을 쉽게 만들기 위해 가능한 한 가깝게 만들고 있습니다. 658 | 659 | ## 정적 분석 도구 660 | 661 | 새로운 표준은 언어로 수 많은 새 문법을 가져오고 있으며 정적 분석 도구는 이를 그대로 활용합니다. 662 | 663 | ### 코드 검사기 (Linter) 664 | 665 | 코드 검사 도구 중 가장 인기있는 도구는 [ESLint](http://eslint.org)이며, 이에 따라 공식적으로 [`babel-eslint`](https://github.com/babel/babel-eslint)를 제공하고 있습니다. 666 | 667 | 먼저 `eslint`와 `babel-eslint`를 설치합니다. 668 | 669 | ```sh 670 | $ npm install --save-dev eslint babel-eslint 671 | ``` 672 | 673 | 그 다음 프로젝트에 새 `.eslintrc` 파일을 만들거나 이미 존재하는 설정에서 `파서`로 `babel-eslint`를 사용하도록 설정합니다. 674 | 675 | ```diff 676 | { 677 | + "parser": "babel-eslint", 678 | "rules": { 679 | ... 680 | } 681 | } 682 | ``` 683 | 684 | 이제 `package.json`의 스크립트에 `lint` 작업을 추가합니다: 685 | 686 | ```diff 687 | { 688 | "name": "my-module", 689 | "scripts": { 690 | + "lint": "eslint my-files.js" 691 | }, 692 | "devDependencies": { 693 | "babel-eslint": "...", 694 | "eslint": "..." 695 | } 696 | } 697 | ``` 698 | 699 | 그리고 작업을 실행하면 모든 설정이 완료됩니다. 700 | 701 | ```sh 702 | $ npm run lint 703 | ``` 704 | 705 | 더 자세한 사항은 [`babel-eslint`](https://github.com/babel/babel-eslint) 또는 [`eslint`](http://eslint.org) 문서를 참고하세요. 706 | 707 | ### 코드 스타일 708 | 709 | > JSCS has merged with ESLint, so checkout Code Styling with ESLint. 710 | 711 | JSCS는 코드 검사의 추가 단계에 있어서 코딩 스타일 자체를 점검하는 매우 인기 있는 코드 검사 도구입니다. Babel과 JSCS 프로젝트의 핵심 관리자 ([@hzoo](https://github.com/hzoo))는 공식적으로 JSCS와의 통합을 제공하고 있습니다. 712 | 713 | 더 나은 방법으로는, JSCS 자체의 `--esnext` 옵션을 통해 쉽게 Babel과 통합하는 방법도 있습니다: 714 | 715 | $ jscs . --esnext 716 | 717 | 718 | CLI에서 실행하거나 `.jscsrc` 파일에 `esnext` 옵션을 추가해도 됩니다. 719 | 720 | ```diff 721 | { 722 | "preset": "airbnb", 723 | + "esnext": true 724 | } 725 | ``` 726 | 727 | 더 자세한 정보는 [`babel-jscs`](https://github.com/jscs-dev/babel-jscs) 또는 [`jscs`](http://jscs.info) 문서를 참고하세요. 728 | 729 | 734 | 735 | ### 문서 736 | 737 | Babel, ES2015, Flow를 사용함으로써 코드의 많은 부분을 추론할 수 있습니다. [documentation.js](http://documentation.js.org)를 사용하면 자세한 API 문서를 쉽게 생성할 수 있습니다. 738 | 739 | Documentation.js는 Flow 표기법이 코드 내에서 타입을 정의함과 동시에 최신의 문법을 지원하기 위해 내부적으로 Babel을 사용합니다. 740 | 741 | ## 프레임워크 742 | 743 | 모든 주요 JavaScript 프레임워크의 API들은 이제 언어의 미래를 향해 초점이 맞춰졌습니다. 이 때문에 툴링에 많은 일이 진행되고 있습니다. 744 | 745 | 프레임워크들은 Babel을 사용하는 것뿐만 아니라 확장하여 사용자 경험을 더 강화할 기회가 있습니다. 746 | 747 | ### React 748 | 749 | React는 극적으로 ES2015의 클래스에 맞춰 API를 변경했습니다. ([업데이트된 API는 이곳에서 확인](https://babeljs.io/blog/2015/06/07/react-on-es6-plus)) 더욱이, React는 JSX 구문의 컴파일을 Babel에 의존하며 Babel을 사용함으로써 그들의 커스텀 툴의 사용을 반대합니다. `babel-preset-react` 패키지와 함께 [위의 절차](#babel-preset-react)에 따라 시작할 수 있습니다.. 750 | 751 | React 커뮤니티는 Babel과 함께 성장합니다. [커뮤니티에 의해 만들어진](https://www.npmjs.com/search?q=babel-plugin+react) 트랜스폼의 개수가 상당해졌습니다.. 752 | 753 | 가장 주목할 것은 몇 가지의 [React-specific transforms](https://github.com/gaearon/babel-plugin-react-transform#transforms)과 함께 *hot module reloading* 그리고 디버깅 유틸리티를 활성화 시킬 수 있는 [`babel-plugin-react-transform`](https://github.com/gaearon/babel-plugin-react-transform)입니다. 754 | 755 | 760 | 761 | ## 텍스트 편집기와 IDE 762 | 763 | Babel과 함께 ES2015와 JSX와 Flow 문법을 사용하는 것은 매우 유용할 수 있습니다. 하지만 텍스트 편집기가 지원하지 않는 경우 정말 좋지 않은 경험이 될 수 있습니다. 이러한 이유로 사용하는 IDE와 함께 Babel 플러그인을 사용하는 방법을 알아보고 싶을 것입니다. 다음을 참고하세요: 764 | 765 | * [Sublime Text](https://github.com/babel/babel-sublime) 766 | * [Atom](https://atom.io/packages/language-babel) 767 | * [Vim](https://github.com/jbgutierrez/vim-babel) 768 | * [WebStorm](https://babeljs.io/docs/setup/#webstorm) 769 | 770 | 775 | 776 | * * * 777 | 778 | # Babel 지원 779 | 780 | Babel은 아주 크고 빠르게 성장하는 커뮤니티를 가지고 있으며, 성장하면서 사람들이 확실히 원하는 리소스를 성공적으로 얻을 수 있도록 도움을 주기 위해 노력하고 있습니다. 그래서 우리는 지원을 위해 서로 다른 채널을 제공하고 있습니다. 781 | 782 | 참고로 모든 커뮤니티는 [행동 강령](https://github.com/babel/babel/blob/master/CODE_OF_CONDUCT.md)을 적용받는다는 것을 기억하세요. 만약 행동 강령을 어길 경우, 조치가 취해질 것입니다. 따라서 위 문서를 읽고 다른 이들과 상호작용할 때 유의하시기 바랍니다. 783 | 784 | 우리는 사람들이 커뮤니티에 머무르며 다른 사람에게 지원하는, 자체적인 지원을 하는 커뮤니티를 목표로 하고 있습니다. 만약 다른 이들이 질문하고 있고 스스로가 이 질문에 대한 답을 안다면, 약간의 시간을 들여 그들을 도와주세요. 최대한 친절하고 이해하려 노력해주세요. 785 | 786 | ## Babel 포럼 787 | 788 | [Discourse](http://www.discourse.org)는 호스팅 버전의 포럼 소프트웨어를 무료로 우리에게 제공하고 있습니다. (그리고 우리는 그들을 매우 사랑합니다!) 만약 포럼에 볼일이 있다면 [discuss.babeljs.io](https://discuss.babeljs.io)에 들러주세요.. 789 | 790 | ## Babel 채팅 791 | 792 | 모두가 [Slack](https://slack.com)을 사랑합니다. 만약 즉각적인 커뮤니티 지원을 알아보고 있다면 [slack.babeljs.io](https://slack.babeljs.io)에 참여하여 도움을 요청하세요. 793 | 794 | 799 | 800 | ## Babel 이슈 801 | 802 | Babel uses the issue tracker provided by [Github](http://github.com). 803 | 804 | You can see all the open and closed issues on [Github](https://github.com/babel/babel/issues). 805 | 806 | 만약 새로운 이슈를 만들고 싶다면: 807 | 808 | * [먼저 해당 이슈가 이미 있는지 검색하세요](https://github.com/babel/babel/issues) 809 | * [Create a new bug report](https://github.com/babel/babel/issues/new) or [request a new feature](https://github.com/babel/babel/issues/new) 810 | 811 | ### 멋진 Babel 버그 보고 생성 812 | 813 | 가끔 Babel의 이슈는 원격으로 디버깅하기 상당히 어려울 때가 있습니다, 따라서 우리는 가능한 한 모든 도움을 받아야 합니다. 약간의 시간을 들여 정말 멋진 버그 리포트를 작성하여 개시한다면 해당 문제가 빠르게 해결되는 데 큰 도움이 됩니다. 814 | 815 | 첫째, 문제를 고립시킵니다. 설치 과정이 문제의 모든 부분에서 영향을 미치고 있을 가능성이 큽니다. 만약 문제가 코드내에 있다면, 같은 문제가 발생하도록 최대한 코드를 줄여주세요. 816 | 817 | > [작업중] 818 | 819 | * * * 820 | 821 | > ***향후 업데이트에 대한 내용은 Twitter의 [@thejameskyle](https://twitter.com/thejameskyle)를 팔로우하세요.*** -------------------------------------------------------------------------------- /translations/zh-Hant/user-handbook.md: -------------------------------------------------------------------------------- 1 | # Babel 使用手冊 2 | 3 | 本文件包含了[Babel](https://babeljs.io)及其相關工具的所有資訊。 4 | 5 | [![cc-by-4.0](https://licensebuttons.net/l/by/4.0/80x15.png)](http://creativecommons.org/licenses/by/4.0/) 6 | 7 | 本使用手冊也提供了其它語系的版本,請參閱[讀我檔案](/README.md)以獲得完整清單。 8 | 9 | # 目錄 10 | 11 | * [簡介](#toc-introduction) 12 | * [安裝 Babel](#toc-setting-up-babel) 13 | * [`babel-cli`](#toc-babel-cli) 14 | * [在專案底下使用 Babel CLI](#toc-running-babel-cli-from-within-a-project) 15 | * [`babel-register`](#toc-babel-register) 16 | * [`babel-node`](#toc-babel-node) 17 | * [`babel-core`](#toc-babel-core) 18 | * [設定 Babel](#toc-configuring-babel) 19 | * [`.babelrc`](#toc-babelrc) 20 | * [`babel-preset-es2015`](#toc-babel-preset-es2015) 21 | * [`babel-preset-react`](#toc-babel-preset-react) 22 | * [`babel-preset-stage-x`](#toc-babel-preset-stage-x) 23 | * [執行已轉換的程式碼](#toc-executing-babel-generated-code) 24 | * [`babel-polyfill`](#toc-babel-polyfill) 25 | * [`babel-runtime`](#toc-babel-runtime) 26 | * [Babel 進階設定](#toc-configuring-babel-advanced) 27 | * [手動指定外掛](#toc-manually-specifying-plugins) 28 | * [外掛選項](#toc-plugin-options) 29 | * [基於環境的 Babel 客製化](#toc-customizing-babel-based-on-environment) 30 | * [撰寫自己的 preset](#toc-making-your-own-preset) 31 | * [其他工具](#toc-babel-and-other-tools) 32 | * [靜態分析工具](#toc-static-analysis-tools) 33 | * [Linting](#toc-linting) 34 | * [Code Style](#toc-code-style) 35 | * [撰寫說明文件](#toc-documentation) 36 | * [Frameworks](#toc-frameworks) 37 | * [React](#toc-react) 38 | * [IDE 及編輯器](#toc-text-editors-and-ides) 39 | * [技術支援](#toc-babel-support) 40 | * [Babel Forum](#toc-babel-forum) 41 | * [Babel Chat](#toc-babel-chat) 42 | * [Babel Issues](#toc-babel-issues) 43 | * [Creating an awesome Babel bug report](#toc-creating-an-awesome-babel-bug-report) 44 | 45 | # 簡介 46 | 47 | Babel 是個 JavaScript 通用型多功能編譯器。藉由 Babel ,你可享受到(或創建出)新世代的 JavaScript 及功能。 48 | 49 | JavaScript 作為一種不斷演進的程式語言,新功能的規格制定和提議不斷推陳出新。 使用 Babel 可讓你在這些新功能廣為普及之前就先行上手。 50 | 51 | Babel 靠的就是把你依據最新標準所寫下的程式碼編譯成時下最普及版本。 這種程序叫程式碼對程式碼編譯(source-to-source compiling),亦稱之為「轉譯」(transpiling)。 52 | 53 | 舉例來說,Babel 能將 ES2015 的新語法,arrow function: 54 | 55 | ```js 56 | const square = n => n * n; 57 | ``` 58 | 59 | 轉譯成: 60 | 61 | ```js 62 | const square = function square(n) { 63 | return n * n; 64 | }; 65 | ``` 66 | 67 | 不過 Babel 能做的不僅如此,它能支援擴充語法,例如能支援 React 的 JSX 語法,以及能進行靜態型別檢查的 Flow 語法。 68 | 69 | 而且在 Babel 裡,一切都是以外掛的形式存在。任何人都可創作自己的外掛,並藉由 Babel 的威力來做任何事。 70 | 71 | *甚至更進一步地*,Babel 自身被解構成數個核心模組,任何人都可用它們來打造新一代的 JavaScript 工具。 72 | 73 | 目前已有許多人這麼做了,整個環繞著 Babel 的生態圈蓬勃發展,充滿著多樣性。 在這份手冊裡,我會談到如何被用 Babel 的內建工具,以及這社群裡的一些實用的東西。 74 | 75 | > ***進一步的最新資訊,請追蹤[@thejameskyle](https://twitter.com/thejameskyle)的 Twitter 帳號。*** 76 | 77 | * * * 78 | 79 | # 安裝 Babel 80 | 81 | 由於 JavaScript 社群裡並沒有統一的建置工具、程式架構、或平臺之類的,Babel 對於所有主流工具整合都有正式的支援。 從 Gulp 到 Browserify、從 Ember 到 Meteor,無論你的建置環境如何設置,Babel 可能都正式整合進來了。 82 | 83 | 基於本手冊的宗旨,我們只會提到 Babel 內建的安裝方式。不過您可參閱互動式的[安裝頁面](http://babeljs.io/docs/setup)來得知其他整合方式的詳情。 84 | 85 | > **注意:**本指南會提到一些命令列工具,例如:`node` 和 `npm`。在閱讀下去之前,請確保您對這些工具有夠的了解。 86 | 87 | ## `babel-cli` 88 | 89 | Babel 的命令列介面(CLI)是編譯檔案最簡單的方法。 90 | 91 | 我們先以全域安裝的方式來學些基本的 92 | 93 | ```sh 94 | $ npm install --global babel-cli 95 | ``` 96 | 97 | 我們可以像這樣來編譯我們的第一個檔案了: 98 | 99 | ```sh 100 | $ babel my-file.js 101 | ``` 102 | 103 | 這樣會把編譯結果直接輸出到你的終端機上。要讓它輸出到檔案,我們得指定:`--out-file` 或 `-o`. 104 | 105 | ```sh 106 | $ babel example.js --out-file compiled.js 107 | # or 108 | $ babel example.js -o compiled.js 109 | ``` 110 | 111 | 如果我們想編譯整個目錄內的檔案,並把結果輸出到另一個目錄下,我們可以使用:`--out-dir` 或 `-d`. 112 | 113 | ```sh 114 | $ babel src --out-dir lib 115 | # or 116 | $ babel src -d lib 117 | ``` 118 | 119 | ### 在專案下執行 Babel CLI 120 | 121 | 雖然您*能*在把 Babel 安裝在機器的全域之下,但在各個專案之下,進行**本地**安裝會更適合。 122 | 123 | 這麼做有兩個主要原因: 124 | 125 | 1. 同一臺機器上的兩個專案,各自使用自己的 Babel,能讓您進行個別的更動。 126 | 2. 如此意謂著你的工作環境不會與非必要的東西產生隱性相依,讓你的專案更具可攜性,更容易設置。 127 | 128 | 要進行本地安裝 Babel 命令列,可執行: 129 | 130 | ```sh 131 | $ npm install --save-dev babel-cli 132 | ``` 133 | 134 | > **注意:**既然一般而言,在全域下執行 Babel 不是個好做法。您或許會想解除安裝全域下的 Babel,請執行: 135 | > 136 | > ```sh 137 | $ npm uninstall --global babel-cli 138 | ``` 139 | 140 | 安裝完成後,你的 `package.json` 檔看起來應該像這樣: 141 | 142 | ```json 143 | { 144 | "name": "my-project", 145 | "version": "1.0.0", 146 | "devDependencies": { 147 | "babel-cli": "^6.0.0" 148 | } 149 | } 150 | ``` 151 | 152 | 現在,我們不是直接在命令列下執行 Babel,而是把我們的命令放進 **npm scripts** 裡,使用本地版本的 Babel。 153 | 154 | 只要在你的 `package.json` 檔裡加入 `"scripts"` 欄位,並把對 Babel 的命令放在 `build` 之後。. 155 | 156 | ```diff 157 | { 158 | "name": "my-project", 159 | "version": "1.0.0", 160 | + "scripts": { 161 | + "build": "babel src -d lib" 162 | + }, 163 | "devDependencies": { 164 | "babel-cli": "^6.0.0" 165 | } 166 | } 167 | ``` 168 | 169 | 現在,我們可以從終端機執行: 170 | 171 | ```js 172 | npm run build 173 | ``` 174 | 175 | 這樣就能跟之前一樣地執行 Babel 了,只不過使用的是本地的版本。 176 | 177 | ## `babel-register` 178 | 179 | 下個經常使用 Babel 的方式是透過 `babel-register`。這種方式,只要有所需的檔案就能執行 Babel 了,這樣或許能跟你的設置做出更好的整合。 180 | 181 | 但是請注意這並不適合在正式環境中使用。 部署以此法編譯出的程式並不是好做法。 在部署之前,先把程式編譯好才比較好。 However this works quite well for build scripts or other things that you run locally. 182 | 183 | 首先,我們在專案中建立一個 `index.js` 檔。 184 | 185 | ```js 186 | console.log("Hello world!"); 187 | ``` 188 | 189 | 如果我們執行 `node index.js`,Babel 不會編譯它。我們得安裝 `babel-register`. 190 | 191 | 首先,安裝 `babel-register`. 192 | 193 | ```sh 194 | $ npm install --save-dev babel-register 195 | ``` 196 | 197 | 接著在專案中建立一個 `register.js` 檔,並在其中加入下列程式碼: 198 | 199 | ```js 200 | require("babel-register"); 201 | require("./index.js"); 202 | ``` 203 | 204 | 這麼做是在 Node 的模組系統中*注冊*Babel,並且開始編譯所有被 `require` 的檔案。 205 | 206 | 現在,我們可以用 `register.js` 取代 `node index.js` 了。 207 | 208 | ```sh 209 | $ node register.js 210 | ``` 211 | 212 | > **注意:**您不能在想編譯的檔案中注冊 Babel。因為 node 會在 Babel 編譯它前就先執行它。 213 | > 214 | > ```js 215 | require("babel-register"); 216 | // not compiled: 217 | console.log("Hello world!"); 218 | ``` 219 | 220 | ## `babel-node` 221 | 222 | 如果您只是透過 `node` 命令列介面來執行某些程式,整合 Babel 的最簡單方式可能就是使用 `babel-node` 命令列介面了。大體上而言,它可算是 `node` 命令列介面的替代品。 223 | 224 | 但是請注意這並不適合在正式環境中使用。 部署以此法編譯出的程式並不是好做法。 在部署之前,先把程式編譯好才比較好。 However this works quite well for build scripts or other things that you run locally. 225 | 226 | 首先,請確定您己安裝了 `babel-cli` 227 | 228 | ```sh 229 | $ npm install --save-dev babel-cli 230 | ``` 231 | 232 | > **Note:** If you are wondering why we are installing this locally, please read the [Running Babel CLI from within a project](#toc-running-babel-cli-from-within-a-project) section above. 233 | 234 | 然後在任何您執行 `node` 的地方,以 `babel-node` 取代之。. 235 | 236 | 如果您使用 npm `scripts`,您只需: 237 | 238 | ```diff 239 | { 240 | "scripts": { 241 | - "script-name": "node script.js" 242 | + "script-name": "babel-node script.js" 243 | } 244 | } 245 | ``` 246 | 247 | 不然的話,你得指明 `babel-node` 的完整路徑。 248 | 249 | ```diff 250 | - node script.js 251 | + ./node_modules/.bin/babel-node script.js 252 | ``` 253 | 254 | > 提示:你也可使用 [`npm-run`](https://www.npmjs.com/package/npm-run). 255 | 256 | ## `babel-core` 257 | 258 | 如果您由於某種原因,需要使用程式控制 Babel,您可直接使用 `babel-core` 套件。 259 | 260 | 首先安裝 `babel-core`. 261 | 262 | ```sh 263 | $ npm install babel-core 264 | ``` 265 | 266 | ```js 267 | var babel = require("babel-core"); 268 | ``` 269 | 270 | 如果您的 JavaScript 是字串形式的,您可直接使用 `babel.transform` 編譯它。. 271 | 272 | ```js 273 | babel.transform("code();", options); 274 | // => { code, map, ast } 275 | ``` 276 | 277 | 如果是檔案形式的,您可選擇使用非同步 API: 278 | 279 | ```js 280 | babel.transformFile("filename.js", options, function(err, result) { 281 | result; // => { code, map, ast } 282 | }); 283 | ``` 284 | 285 | 或是同步 API: 286 | 287 | ```js 288 | babel.transformFileSync("filename.js", options); 289 | // => { code, map, ast } 290 | ``` 291 | 292 | 無論如何,如果您已經有了 Babel 的抽象語法樹(AST),您也可直接將之編譯。 293 | 294 | ```js 295 | babel.transformFromAst(ast, code, options); 296 | // => { code, map, ast } 297 | ``` 298 | 299 | For all of the above methods, `options` refers to https://babeljs.io/docs/usage/api/#options. 300 | 301 | * * * 302 | 303 | # 設定 Babel 304 | 305 | 現在你可能注意到了,單獨執行 Babel 看來除了把 JavaScript 檔案從一處複製到另一處之外,並沒什麼其他的作用。 306 | 307 | 這是因為我們還沒告訴 Babel 要做什麼。 308 | 309 | > 因為 Babel 是個通用型的編譯器,有各式各樣的使用方式。在預設的情況下,它不會做任何事。你得明確告訴 Babel 該做些什麼。 310 | 311 | 您可藉由安裝 **外掛程式** 或 **presets**(一組外掛程式)來指示 Babel 該做些什麼。 312 | 313 | ## `.babelrc` 314 | 315 | 在我們告訴 Babel 做什麼之前,我們需要建立一個組態檔。我們需要做的只是建立一個 `.babelrc` 檔,把它放在您的專案的根目錄。剛開始它的內容就像這樣: 316 | 317 | ```js 318 | { 319 | "presets": [], 320 | "plugins": [] 321 | } 322 | ``` 323 | 324 | 這個檔案就是您用來設定 Babel,讓它執行您想做的事。 325 | 326 | > **注意:**儘管您還是有其他方式可把各種選項傳給 Babel,但 `.babelrc` 檔仍是最常規、最好的方式。 327 | 328 | ## `babel-preset-es2015` 329 | 330 | 我們就先從叫 Babel 把 ES2015(最新版的 JavaScrpt 標準,亦稱 ES6)程式碼編譯成 ES5(大多數 JavaScript 環境都支援的版本)程式碼。 331 | 332 | 我們得安裝「ES2015」Babel preset: 333 | 334 | ```sh 335 | $ npm install --save-dev babel-preset-es2015 336 | ``` 337 | 338 | 接著,我們得修改 `.babelrc` 檔來把那 preset 包含進來。 339 | 340 | ```diff 341 | { 342 | "presets": [ 343 | + "es2015" 344 | ], 345 | "plugins": [] 346 | } 347 | ``` 348 | 349 | ## `babel-preset-react` 350 | 351 | 要安裝 React 很容易,只需安裝 preset: 352 | 353 | ```sh 354 | $ npm install --save-dev babel-preset-react 355 | ``` 356 | 357 | 然後把那 preset 加入您的 `.babelrc` 檔即可: 358 | 359 | ```diff 360 | { 361 | "presets": [ 362 | "es2015", 363 | + "react" 364 | ], 365 | "plugins": [] 366 | } 367 | ``` 368 | 369 | ## `babel-preset-stage-x` 370 | 371 | JavaScript 還有些提議案正經過 TC39(ECMAScript 標準背後的技術委員會)的審議程序,準備加入標準。 372 | 373 | 這個程序被分為五個階段(0-4)。 提案獲得越多關注就越有可能被採納。它們通過各個階段審議,最後在階段4被接受並納入標準。 374 | 375 | 這些提案被包裹成四個不同的 preset: 376 | 377 | * `babel-preset-stage-0` 378 | * `babel-preset-stage-1` 379 | * `babel-preset-stage-2` 380 | * `babel-preset-stage-3` 381 | 382 | > 注意階段4的 preset 並不存在,因為它就是上面提到的 `es2015` preset 383 | 384 | 上述各階段 preset 都相依於它下個階段的 preset,例如:`babel-preset-stage-1` 相依於 `babel-preset-stage-2`,而後者又相依於 `babel-preset-stage-3`. 385 | 386 | 要安裝您感興趣的階段只需: 387 | 388 | ```sh 389 | $ npm install --save-dev babel-preset-stage-2 390 | ``` 391 | 392 | 然後您就可把它加入您的 `.babelrc` 組態檔. 393 | 394 | ```diff 395 | { 396 | "presets": [ 397 | "es2015", 398 | "react", 399 | + "stage-2" 400 | ], 401 | "plugins": [] 402 | } 403 | ``` 404 | 405 | * * * 406 | 407 | # 執行已轉換的程式碼 408 | 409 | So you've compiled your code with Babel, but this is not the end of the story. 410 | 411 | ## `babel-polyfill` 412 | 413 | Almost all futuristic JavaScript syntax can be compiled with Babel, but the same is not true for APIs. 414 | 415 | For example, the following code has an arrow function that needs to be compiled: 416 | 417 | ```js 418 | function addAll() { 419 | return Array.from(arguments).reduce((a, b) => a + b); 420 | } 421 | ``` 422 | 423 | Which turns into this: 424 | 425 | ```js 426 | function addAll() { 427 | return Array.from(arguments).reduce(function(a, b) { 428 | return a + b; 429 | }); 430 | } 431 | ``` 432 | 433 | However, this still won't work everywhere because `Array.from` doesn't exist in every JavaScript environment. 434 | 435 | Uncaught TypeError: Array.from is not a function 436 | 437 | 438 | To solve this problem we use something called a [Polyfill](https://remysharp.com/2010/10/08/what-is-a-polyfill). Simply put, a polyfill is a piece of code that replicates a native api that does not exist in the current runtime. Allowing you to use APIs such as `Array.from` before they are available. 439 | 440 | Babel uses the excellent [core-js](https://github.com/zloirock/core-js) as its polyfill, along with a customized [regenerator](https://github.com/facebook/regenerator) runtime for getting generators and async functions working. 441 | 442 | To include the Babel polyfill, first install it with npm: 443 | 444 | ```sh 445 | $ npm install --save babel-polyfill 446 | ``` 447 | 448 | Then simply include the polyfill at the top of any file that requires it: 449 | 450 | ```js 451 | import "babel-polyfill"; 452 | ``` 453 | 454 | ## `babel-runtime` 455 | 456 | In order to implement details of ECMAScript specs, Babel will use "helper" methods in order to keep the generated code clean. 457 | 458 | Since these helpers can get pretty long, and they get added to the top of every file you can move them into a single "runtime" which gets required. 459 | 460 | Start by installing `babel-plugin-transform-runtime` and `babel-runtime`: 461 | 462 | ```sh 463 | $ npm install --save-dev babel-plugin-transform-runtime 464 | $ npm install --save babel-runtime 465 | ``` 466 | 467 | Then update your `.babelrc`: 468 | 469 | ```diff 470 | { 471 | "plugins": [ 472 | + "transform-runtime", 473 | "transform-es2015-classes" 474 | ] 475 | } 476 | ``` 477 | 478 | Now Babel will compile code like the following: 479 | 480 | ```js 481 | class Foo { 482 | method() {} 483 | } 484 | ``` 485 | 486 | Into this: 487 | 488 | ```js 489 | import _classCallCheck from "babel-runtime/helpers/classCallCheck"; 490 | import _createClass from "babel-runtime/helpers/createClass"; 491 | 492 | let Foo = function () { 493 | function Foo() { 494 | _classCallCheck(this, Foo); 495 | } 496 | 497 | _createClass(Foo, [{ 498 | key: "method", 499 | value: function method() {} 500 | }]); 501 | 502 | return Foo; 503 | }(); 504 | ``` 505 | 506 | Rather than putting the `_classCallCheck` and `_createClass` helpers in every single file where they are needed. 507 | 508 | * * * 509 | 510 | # Babel 進階設定 511 | 512 | Most people can get by using Babel with just the built-in presets, but Babel exposes much finer-grained power than that. 513 | 514 | ## 手動指定外掛 515 | 516 | Babel presets are simply collections of pre-configured plugins, if you want to do something differently you manually specify plugins. This works almost exactly the same way as presets. 517 | 518 | First install a plugin: 519 | 520 | ```sh 521 | $ npm install --save-dev babel-plugin-transform-es2015-classes 522 | ``` 523 | 524 | Then add the `plugins` field to your `.babelrc`. 525 | 526 | ```diff 527 | { 528 | + "plugins": [ 529 | + "transform-es2015-classes" 530 | + ] 531 | } 532 | ``` 533 | 534 | This gives you much finer grained control over the exact transforms you are running. 535 | 536 | For a full list of official plugins see the [Babel Plugins page](http://babeljs.io/docs/plugins/). 537 | 538 | Also take a look at all the plugins that have been [built by the community](https://www.npmjs.com/search?q=babel-plugin). If you would like to learn how to write your own plugin read the [Babel Plugin Handbook](plugin-handbook.md). 539 | 540 | ## 外掛選項 541 | 542 | Many plugins also have options to configure them to behave differently. For example, many transforms have a "loose" mode which drops some spec behavior in favor of simpler and more performant generated code. 543 | 544 | To add options to a plugin, simply make the following change: 545 | 546 | ```diff 547 | { 548 | "plugins": [ 549 | - "transform-es2015-classes" 550 | + ["transform-es2015-classes", { "loose": true }] 551 | ] 552 | } 553 | ``` 554 | 555 | > I'll be working on updates to the plugin documentation to detail every option in the coming weeks. [Follow me for updates](https://twitter.com/thejameskyle). 556 | 557 | ## 基於環境的 Babel 客製化 558 | 559 | Babel plugins solve many different tasks. Many of them are development tools that can help you debugging your code or integrate with tools. There are also a lot of plugins that are meant for optimizing your code in production. 560 | 561 | For this reason, it is common to want Babel configuration based on the environment. You can do this easily with your `.babelrc` file. 562 | 563 | ```diff 564 | { 565 | "presets": ["es2015"], 566 | "plugins": [], 567 | + "env": { 568 | + "development": { 569 | + "plugins": [...] 570 | + }, 571 | + "production": { 572 | + "plugins": [...] 573 | + } 574 | } 575 | } 576 | ``` 577 | 578 | Babel will enable configuration inside of `env` based on the current environment. 579 | 580 | The current environment will use `process.env.BABEL_ENV`. When `BABEL_ENV` is not available, it will fallback to `NODE_ENV`, and if that is not available it will default to `"development"`. 581 | 582 | **Unix** 583 | 584 | ```sh 585 | $ BABEL_ENV=production [COMMAND] 586 | $ NODE_ENV=production [COMMAND] 587 | ``` 588 | 589 | **Windows** 590 | 591 | ```sh 592 | $ SET BABEL_ENV=production 593 | $ [COMMAND] 594 | ``` 595 | 596 | > **Note:** `[COMMAND]` is whatever you use to run Babel (ie. `babel`, `babel-node`, or maybe just `node` if you are using the register hook). 597 | > 598 | > **Tip:** If you want your command to work across unix and windows platforms then use [`cross-env`](https://www.npmjs.com/package/cross-env). 599 | 600 | ## 撰寫自己的 preset 601 | 602 | Manually specifying plugins? Plugin options? Environment-based settings? All this configuration might seem like a ton of repetition for all of your projects. 603 | 604 | For this reason, we encourage the community to create their own presets. This could be a preset for the specific [node version](https://github.com/leebenson/babel-preset-node5) you are running, or maybe a preset for your [entire](https://github.com/cloudflare/babel-preset-cf) [company](https://github.com/airbnb/babel-preset-airbnb). 605 | 606 | It's easy to create a preset. Say you have this `.babelrc` file: 607 | 608 | ```js 609 | { 610 | "presets": [ 611 | "es2015", 612 | "react" 613 | ], 614 | "plugins": [ 615 | "transform-flow-strip-types" 616 | ] 617 | } 618 | ``` 619 | 620 | All you need to do is create a new project following the naming convention `babel-preset-*` (please be responsible with this namespace), and create two files. 621 | 622 | First, create a new `package.json` file with the necessary `dependencies` for your preset. 623 | 624 | ```js 625 | { 626 | "name": "babel-preset-my-awesome-preset", 627 | "version": "1.0.0", 628 | "author": "James Kyle ", 629 | "dependencies": { 630 | "babel-preset-es2015": "^6.3.13", 631 | "babel-preset-react": "^6.3.13", 632 | "babel-plugin-transform-flow-strip-types": "^6.3.15" 633 | } 634 | } 635 | ``` 636 | 637 | Then create an `index.js` file that exports the contents of your `.babelrc` file, replacing plugin/preset strings with `require` calls. 638 | 639 | ```js 640 | module.exports = { 641 | presets: [ 642 | require("babel-preset-es2015"), 643 | require("babel-preset-react") 644 | ], 645 | plugins: [ 646 | require("babel-plugin-transform-flow-strip-types") 647 | ] 648 | }; 649 | ``` 650 | 651 | Then simply publish this to npm and you can use it like you would any preset. 652 | 653 | * * * 654 | 655 | # 其他工具 656 | 657 | Babel is pretty straight forward to setup once you get the hang of it, but it can be rather difficult navigating how to set it up with other tools. However, we try to work closely with other projects in order to make the experience as easy as possible. 658 | 659 | ## 靜態分析工具 660 | 661 | Newer standards bring a lot of new syntax to the language and static analysis tools are just starting to take advantage of it. 662 | 663 | ### Linting 664 | 665 | One of the most popular tools for linting is [ESLint](http://eslint.org), because of this we maintain an official [`babel-eslint`](https://github.com/babel/babel-eslint) integration. 666 | 667 | First install `eslint` and `babel-eslint`. 668 | 669 | ```sh 670 | $ npm install --save-dev eslint babel-eslint 671 | ``` 672 | 673 | Next create or use the existing `.eslintrc` file in your project and set the `parser` as `babel-eslint`. 674 | 675 | ```diff 676 | { 677 | + "parser": "babel-eslint", 678 | "rules": { 679 | ... 680 | } 681 | } 682 | ``` 683 | 684 | Now add a `lint` task to your npm `package.json` scripts: 685 | 686 | ```diff 687 | { 688 | "name": "my-module", 689 | "scripts": { 690 | + "lint": "eslint my-files.js" 691 | }, 692 | "devDependencies": { 693 | "babel-eslint": "...", 694 | "eslint": "..." 695 | } 696 | } 697 | ``` 698 | 699 | Then just run the task and you will be all setup. 700 | 701 | ```sh 702 | $ npm run lint 703 | ``` 704 | 705 | For more information consult the [`babel-eslint`](https://github.com/babel/babel-eslint) or [`eslint`](http://eslint.org) documentation. 706 | 707 | ### Code Style 708 | 709 | > JSCS has merged with ESLint, so checkout Code Styling with ESLint. 710 | 711 | JSCS is an extremely popular tool for taking linting a step further into checking the style of the code itself. A core maintainer of both the Babel and JSCS projects ([@hzoo](https://github.com/hzoo)) maintains an official integration with JSCS. 712 | 713 | Even better, this integration now lives within JSCS itself under the `--esnext` option. So integrating Babel is as easy as: 714 | 715 | $ jscs . --esnext 716 | 717 | 718 | From the cli, or adding the `esnext` option to your `.jscsrc` file. 719 | 720 | ```diff 721 | { 722 | "preset": "airbnb", 723 | + "esnext": true 724 | } 725 | ``` 726 | 727 | For more information consult the [`babel-jscs`](https://github.com/jscs-dev/babel-jscs) or [`jscs`](http://jscs.info) documentation. 728 | 729 | 734 | 735 | ### 撰寫說明文件 736 | 737 | Using Babel, ES2015, and Flow you can infer a lot about your code. Using [documentation.js](http://documentation.js.org) you can generate detailed API documentation very easily. 738 | 739 | Documentation.js uses Babel behind the scenes to support all of the latest syntax including Flow annotations in order to declare the types in your code. 740 | 741 | ## Frameworks 742 | 743 | All of the major JavaScript frameworks are now focused on aligning their APIs around the future of the language. Because of this, there has been a lot of work going into the tooling. 744 | 745 | Frameworks have the opportunity not just to use Babel but to extend it in ways that improve their users' experience. 746 | 747 | ### React 748 | 749 | React has dramatically changed their API to align with ES2015 classes ([Read about the updated API here](https://babeljs.io/blog/2015/06/07/react-on-es6-plus)). Even further, React relies on Babel to compile it's JSX syntax, deprecating it's own custom tooling in favor of Babel. You can start by setting up the `babel-preset-react` package following the [instructions above](#babel-preset-react). 750 | 751 | The React community took Babel and ran with it. There are now a number of transforms [built by the community](https://www.npmjs.com/search?q=babel-plugin+react). 752 | 753 | Most notably the [`babel-plugin-react-transform`](https://github.com/gaearon/babel-plugin-react-transform) plugin which combined with a number of [React-specific transforms](https://github.com/gaearon/babel-plugin-react-transform#transforms) can enable things like *hot module reloading* and other debugging utilities. 754 | 755 | 760 | 761 | ## IDE 及編輯器 762 | 763 | Introducing ES2015, JSX, and Flow syntax with Babel can be helpful, but if your text editor doesn't support it then it can be a really bad experience. For this reason you will want to setup your text editor or IDE with a Babel plugin. 764 | 765 | * [Sublime Text](https://github.com/babel/babel-sublime) 766 | * [Atom](https://atom.io/packages/language-babel) 767 | * [Vim](https://github.com/jbgutierrez/vim-babel) 768 | * [WebStorm](https://babeljs.io/docs/setup/#webstorm) 769 | 770 | 775 | 776 | * * * 777 | 778 | # 技術支援 779 | 780 | Babel has a very large and quickly growing community, as we grow we want to ensure that people have all the resources they need to be successful. So we provide a number of different channels for getting support. 781 | 782 | Remember that across all of these communities we enforce a [Code of Conduct](https://github.com/babel/babel/blob/master/CODE_OF_CONDUCT.md). If you break the Code of Conduct, action will be taken. So please read it and be conscious of it when interacting with others. 783 | 784 | We are also looking to grow a self-supporting community, for people who stick around and support others. If you find someone asking a question you know the answer to, take a few minutes and help them out. Try your best to be kind and understanding when doing so. 785 | 786 | ## Babel Forum 787 | 788 | [Discourse](http://www.discourse.org) has provided us with a hosted version of their forum software for free (and we love them for it!). If forums are your thing please stop by [discuss.babeljs.io](https://discuss.babeljs.io). 789 | 790 | ## Babel Chat 791 | 792 | Everyone loves [Slack](https://slack.com). If you're looking for immediate support from the community then come chat with us at [slack.babeljs.io](https://slack.babeljs.io). 793 | 794 | 799 | 800 | ## Babel Issues 801 | 802 | Babel uses the issue tracker provided by [Github](http://github.com). 803 | 804 | You can see all the open and closed issues on [Github](https://github.com/babel/babel/issues). 805 | 806 | If you want to open a new issue: 807 | 808 | * [Search for an existing issue](https://github.com/babel/babel/issues) 809 | * [Create a new bug report](https://github.com/babel/babel/issues/new) or [request a new feature](https://github.com/babel/babel/issues/new) 810 | 811 | ### Creating an awesome Babel bug report 812 | 813 | Babel issues can sometimes be very difficult to debug remotely, so we need all the help we can get. Spending a few more minutes crafting a really nice bug report can help get your problem solved significantly faster. 814 | 815 | First, try isolating your problem. It's extremely unlikely that every part of your setup is contributing to the problem. If your problem is a piece of input code, try deleting as much code as possible that still causes an issue. 816 | 817 | > [WIP] 818 | 819 | * * * 820 | 821 | > ***進一步的最新資訊,請追蹤[@thejameskyle](https://twitter.com/thejameskyle)的 Twitter 帳號。*** -------------------------------------------------------------------------------- /translations/ja/user-handbook.md: -------------------------------------------------------------------------------- 1 | # Babel User Handbook 2 | 3 | このドキュメントはあなたが知りたい[Babel](https://babeljs.io)やその関連ツールの使い方をカバーします。 4 | 5 | [![cc-by-4.0](https://licensebuttons.net/l/by/4.0/80x15.png)](http://creativecommons.org/licenses/by/4.0/) 6 | 7 | このハンドブックは他の言語にも翻訳されています。全ての言語のリストについては[README](/README.md)を参照してください。 8 | 9 | # 目次 10 | 11 | * [イントロダクション](#toc-introduction) 12 | * [Babel のセットアップ](#toc-setting-up-babel) 13 | * [`babel-cli`](#toc-babel-cli) 14 | * [プロジェクトでBabel CLI を実行する](#toc-running-babel-cli-from-within-a-project) 15 | * [`babel-register`](#toc-babel-register) 16 | * [`babel-node`](#toc-babel-node) 17 | * [`babel-core`](#toc-babel-core) 18 | * [Babel の設定](#toc-configuring-babel) 19 | * [`.babelrc`](#toc-babelrc) 20 | * [`babel-preset-es2015`](#toc-babel-preset-es2015) 21 | * [`babel-preset-react`](#toc-babel-preset-react) 22 | * [`babel-preset-stage-x`](#toc-babel-preset-stage-x) 23 | * [Babelで生成したコードを実行する](#toc-executing-babel-generated-code) 24 | * [`babel-polyfill`](#toc-babel-polyfill) 25 | * [`babel-runtime`](#toc-babel-runtime) 26 | * [Babel 設定 (高度な)](#toc-configuring-babel-advanced) 27 | * [プラグインを手動で設定](#toc-manually-specifying-plugins) 28 | * [プラグインのオプション](#toc-plugin-options) 29 | * [Customizing Babel based on environment](#toc-customizing-babel-based-on-environment) 30 | * [Making your own preset](#toc-making-your-own-preset) 31 | * [Babel and other tools](#toc-babel-and-other-tools) 32 | * [静的解析ツール](#toc-static-analysis-tools) 33 | * [Lint](#toc-linting) 34 | * [Code Style](#toc-code-style) 35 | * [Documentation](#toc-documentation) 36 | * [フレームワーク](#toc-frameworks) 37 | * [React](#toc-react) 38 | * [テキストエディタ・IDE](#toc-text-editors-and-ides) 39 | * [Babel のサポート](#toc-babel-support) 40 | * [Babel Forum](#toc-babel-forum) 41 | * [Babel Chat](#toc-babel-chat) 42 | * [Babel Issues](#toc-babel-issues) 43 | * [Creating an awesome Babel bug report](#toc-creating-an-awesome-babel-bug-report) 44 | 45 | # イントロダクション 46 | 47 | BabelはJavaScriptのための包括的な多目的コンパイラです。Babelを利用すると、あなたは次世代のJavaScriptを体験するだけではなく、次世代JavaScript用ツールを利用(または作成)することが出来ます。 48 | 49 | Javascripは常に新しい標準規格や提案などによって新機能が実装され続けており、常に進化している言語です。 Babelを使うことによって旧環境でも最新の機能を使えるようになります。 50 | 51 | これを実現するためにBabelは最新の規格で書かれたJavascriptを、現在標準的に対応されているバージョンにコンパイルします。 このコンパイルは、source-to-sourceコンパイル、もしくはトランスパイルと呼ばれます。 52 | 53 | 例えば、Babelは新しいES2015規格のアロー関数シンタックスをこれ: 54 | 55 | ```js 56 | const square = n => n * n; 57 | ``` 58 | 59 | から以下のコードに変換します: 60 | 61 | ```js 62 | const square = function square(n) { 63 | return n * n; 64 | }; 65 | ``` 66 | 67 | しかし、それだけではありませんBabelは様々な文法に対応しており、ReactのJSXシンタックスやFlowの静的型付けにも対応しています。 68 | 69 | さらに、Babelの全てはプラグインになっており、誰でも自由にBabelをフル活用したプラグインを開発できます。 70 | 71 | *さらにさらに*、Babelは何個かのコアモジュールに分割されており、次世代のJavascriptツール開発に使えます。 72 | 73 | Babelの開発者コミュニティは広く大きく、上記のリソースをフル活用しています。 このハンドブックの中ではBabelの組み込みツールの使い方と、開発者コミュニティによって作られた便利なツールも取りあげていきます。 74 | 75 | > ***最新の情報を受け取るには、Twitterで[@thejameskyle](https://twitter.com/thejameskyle)をフォローしてください。*** 76 | 77 | * * * 78 | 79 | # Babel のセットアップ 80 | 81 | Since the JavaScript community has no single build tool, framework, platform, etc., Babel has official integrations for all of the major tooling. Everything from Gulp to Browserify, from Ember to Meteor, no matter what your setup looks like there is probably an official integration. 82 | 83 | For the purposes of this handbook, we're just going to cover the built-in ways of setting up Babel, but you can also visit the interactive [setup page](http://babeljs.io/docs/setup) for all of the integrations. 84 | 85 | > **Note:** ここでは`node`や`npm`といったコマンドラインツールの使い方を紹介しません。これらのツールに習熟していることを前提とします。 86 | 87 | ## `babel-cli` 88 | 89 | Babel CLIによって、コマンドラインから Babel で簡単にコンパイルできます。 90 | 91 | グローバルインストールして、基本を学びましょう。 92 | 93 | ```sh 94 | $ npm install --global babel-cli 95 | ``` 96 | 97 | 初めてコンパイルするにはこんな感じにします。 98 | 99 | ```sh 100 | $ babel my-file.js 101 | ``` 102 | 103 | コンパイルした結果がターミナルにそのままダンプされます。ファイルに書き込む際は`--out-file` or `-o`オプションを指定してください。. 104 | 105 | ```sh 106 | $ babel example.js --out-file compiled.js 107 | # or 108 | $ babel example.js -o compiled.js 109 | ``` 110 | 111 | ディレクトリ全体をコンパイルしたい場合は`--out-dir` or `-d`オプションを指定してください. 112 | 113 | ```sh 114 | $ babel src --out-dir lib 115 | # or 116 | $ babel src -d lib 117 | ``` 118 | 119 | ### プロジェクトでBabel CLI を実行する 120 | 121 | While you *can* install Babel CLI globally on your machine, it's much better to install it **locally** project by project. 122 | 123 | There are two primary reasons for this. 124 | 125 | 1. Different projects on the same machine can depend on different versions of Babel allowing you to update one at a time. 126 | 2. It means you do not have an implicit dependency on the environment you are working in. Making your project far more portable and easier to setup. 127 | 128 | We can install Babel CLI locally by running: 129 | 130 | ```sh 131 | $ npm install --save-dev babel-cli 132 | ``` 133 | 134 | > **Note:** Since it's generally a bad idea to run Babel globally you may want to uninstall the global copy by running: 135 | > 136 | > ```sh 137 | $ npm uninstall --global babel-cli 138 | ``` 139 | 140 | After that finishes installing, your `package.json` file should look like this: 141 | 142 | ```json 143 | { 144 | "name": "my-project", 145 | "version": "1.0.0", 146 | "devDependencies": { 147 | "babel-cli": "^6.0.0" 148 | } 149 | } 150 | ``` 151 | 152 | Now instead of running Babel directly from the command line we're going to put our commands in **npm scripts** which will use our local version. 153 | 154 | Simply add a `"scripts"` field to your `package.json` and put the babel command inside there as `build`. 155 | 156 | ```diff 157 | { 158 | "name": "my-project", 159 | "version": "1.0.0", 160 | + "scripts": { 161 | + "build": "babel src -d lib" 162 | + }, 163 | "devDependencies": { 164 | "babel-cli": "^6.0.0" 165 | } 166 | } 167 | ``` 168 | 169 | Now from our terminal we can run: 170 | 171 | ```js 172 | npm run build 173 | ``` 174 | 175 | This will run Babel the same way as before, only now we are using a local copy. 176 | 177 | ## `babel-register` 178 | 179 | The next most common method of running Babel is through `babel-register`. This option will allow you to run Babel just by requiring files, which may integrate with your setup better. 180 | 181 | Note that this is not meant for production use. It's considered bad practice to deploy code that gets compiled this way. It is far better to compile ahead of time before deploying. However this works quite well for build scripts or other things that you run locally. 182 | 183 | `index.js`ファイルをプロジェクトに作成しましょう。 184 | 185 | ```js 186 | console.log("Hello world!"); 187 | ``` 188 | 189 | 仮に`node index.js`を実行していたら、コンパイルされません。代わりに`babel-register`をセットアップしましょう。. 190 | 191 | 初めに、`babel-register`をインストールします. 192 | 193 | ```sh 194 | $ npm install --save-dev babel-register 195 | ``` 196 | 197 | 次に、プロジェクトに`register.js`ファイルを生成し、以下のコードを記述します。 198 | 199 | ```js 200 | require("babel-register"); 201 | require("./index.js"); 202 | ``` 203 | 204 | こうして、Babelをノードのモジュールシステムに登録(*register*) し、 `require`した全ファイルのコンパイルを開始します。 205 | 206 | それでは `node index.js` を実行して ` register.js` を使用してみましょう。 207 | 208 | ```sh 209 | $ node register.js 210 | ``` 211 | 212 | > **Note:** You can't register Babel in the same file that you want to compile. As node is executing the file before Babel has a chance to compile it. 213 | > 214 | > ```js 215 | require("babel-register"); 216 | // not compiled: 217 | console.log("Hello world!"); 218 | ``` 219 | 220 | ## `babel-node` 221 | 222 | If you are just running some code via the `node` CLI the easiest way to integrate Babel might be to use the `babel-node` CLI which largely is just a drop in replacement for the `node` CLI. 223 | 224 | Note that this is not meant for production use. It's considered bad practice to deploy code that gets compiled this way. It is far better to compile ahead of time before deploying. However this works quite well for build scripts or other things that you run locally. 225 | 226 | First make sure that you have `babel-cli` installed. 227 | 228 | ```sh 229 | $ npm install --save-dev babel-cli 230 | ``` 231 | 232 | > **Note:** If you are wondering why we are installing this locally, please read the [Running Babel CLI from within a project](#toc-running-babel-cli-from-within-a-project) section above. 233 | 234 | Then replace wherever you are running `node` with `babel-node`. 235 | 236 | If you are using npm `scripts` you can simply do: 237 | 238 | ```diff 239 | { 240 | "scripts": { 241 | - "script-name": "node script.js" 242 | + "script-name": "babel-node script.js" 243 | } 244 | } 245 | ``` 246 | 247 | Otherwise you'll need to write out the path to `babel-node` itself. 248 | 249 | ```diff 250 | - node script.js 251 | + ./node_modules/.bin/babel-node script.js 252 | ``` 253 | 254 | > Tip: You can also use [`npm-run`](https://www.npmjs.com/package/npm-run). 255 | 256 | ## `babel-core` 257 | 258 | If you need to use Babel programmatically for some reason, you can use the `babel-core` package itself. 259 | 260 | First install `babel-core`. 261 | 262 | ```sh 263 | $ npm install babel-core 264 | ``` 265 | 266 | ```js 267 | var babel = require("babel-core"); 268 | ``` 269 | 270 | If you have a string of JavaScript you can compile it directly using `babel.transform`. 271 | 272 | ```js 273 | babel.transform("code();", options); 274 | // => { code, map, ast } 275 | ``` 276 | 277 | If you are working with files you can use either the asynchronous api: 278 | 279 | ```js 280 | babel.transformFile("filename.js", options, function(err, result) { 281 | result; // => { code, map, ast } 282 | }); 283 | ``` 284 | 285 | Or the synchronous api: 286 | 287 | ```js 288 | babel.transformFileSync("filename.js", options); 289 | // => { code, map, ast } 290 | ``` 291 | 292 | If you already have a Babel AST for whatever reason you may transform from the AST directly. 293 | 294 | ```js 295 | babel.transformFromAst(ast, code, options); 296 | // => { code, map, ast } 297 | ``` 298 | 299 | For all of the above methods, `options` refers to https://babeljs.io/docs/usage/api/#options. 300 | 301 | * * * 302 | 303 | # Babel の設定 304 | 305 | You may have noticed by now that running Babel on its own doesn't seem to do anything other than copy JavaScript files from one location to another. 306 | 307 | This is because we haven't told Babel to do anything yet. 308 | 309 | > Since Babel is a general purpose compiler that gets used in a myriad of different ways, it doesn't do anything by default. You have to explicitly tell Babel what it should be doing. 310 | 311 | You can give Babel instructions on what to do by installing **plugins** or **presets** (groups of plugins). 312 | 313 | ## `.babelrc` 314 | 315 | Before we start telling Babel what to do. We need to create a configuration file. All you need to do is create a `.babelrc` file at the root of your project. Start off with it like this: 316 | 317 | ```js 318 | { 319 | "presets": [], 320 | "plugins": [] 321 | } 322 | ``` 323 | 324 | This file is how you configure Babel to do what you want. 325 | 326 | > **Note:** While you can also pass options to Babel in other ways the `.babelrc` file is convention and is the best way. 327 | 328 | ## `babel-preset-es2015` 329 | 330 | Let's start by telling Babel to compile ES2015 (the newest version of the JavaScript standard, also known as ES6) to ES5 (the version available in most JavaScript environments today). 331 | 332 | We'll do this by installing the "es2015" Babel preset: 333 | 334 | ```sh 335 | $ npm install --save-dev babel-preset-es2015 336 | ``` 337 | 338 | Next we'll modify our `.babelrc` to include that preset. 339 | 340 | ```diff 341 | { 342 | "presets": [ 343 | + "es2015" 344 | ], 345 | "plugins": [] 346 | } 347 | ``` 348 | 349 | ## `babel-preset-react` 350 | 351 | Setting up React is just as easy. Just install the preset: 352 | 353 | ```sh 354 | $ npm install --save-dev babel-preset-react 355 | ``` 356 | 357 | Then add the preset to your `.babelrc` file: 358 | 359 | ```diff 360 | { 361 | "presets": [ 362 | "es2015", 363 | + "react" 364 | ], 365 | "plugins": [] 366 | } 367 | ``` 368 | 369 | ## `babel-preset-stage-x` 370 | 371 | JavaScript also has some proposals that are making their way into the standard through the TC39's (the technical committee behind the ECMAScript standard) process. 372 | 373 | This process is broken through a 5 stage (0-4) process. As proposals gain more traction and are more likely to be accepted into the standard they proceed through the various stages, finally being accepted into the standard at stage 4. 374 | 375 | These are bundled in babel as 4 different presets: 376 | 377 | * `babel-preset-stage-0` 378 | * `babel-preset-stage-1` 379 | * `babel-preset-stage-2` 380 | * `babel-preset-stage-3` 381 | 382 | > Note that there is no stage-4 preset as it is simply the `es2015` preset above. 383 | 384 | Each of these presets requires the preset for the later stages. i.e. `babel-preset-stage-1` requires `babel-preset-stage-2` which requires `babel-preset-stage-3`. 385 | 386 | Simply install the stage you are interested in using: 387 | 388 | ```sh 389 | $ npm install --save-dev babel-preset-stage-2 390 | ``` 391 | 392 | Then you can add it to your `.babelrc` config. 393 | 394 | ```diff 395 | { 396 | "presets": [ 397 | "es2015", 398 | "react", 399 | + "stage-2" 400 | ], 401 | "plugins": [] 402 | } 403 | ``` 404 | 405 | * * * 406 | 407 | # Babelで生成したコードを実行する 408 | 409 | So you've compiled your code with Babel, but this is not the end of the story. 410 | 411 | ## `babel-polyfill` 412 | 413 | Almost all futuristic JavaScript syntax can be compiled with Babel, but the same is not true for APIs. 414 | 415 | For example, the following code has an arrow function that needs to be compiled: 416 | 417 | ```js 418 | function addAll() { 419 | return Array.from(arguments).reduce((a, b) => a + b); 420 | } 421 | ``` 422 | 423 | Which turns into this: 424 | 425 | ```js 426 | function addAll() { 427 | return Array.from(arguments).reduce(function(a, b) { 428 | return a + b; 429 | }); 430 | } 431 | ``` 432 | 433 | However, this still won't work everywhere because `Array.from` doesn't exist in every JavaScript environment. 434 | 435 | Uncaught TypeError: Array.from is not a function 436 | 437 | 438 | To solve this problem we use something called a [Polyfill](https://remysharp.com/2010/10/08/what-is-a-polyfill). Simply put, a polyfill is a piece of code that replicates a native api that does not exist in the current runtime. Allowing you to use APIs such as `Array.from` before they are available. 439 | 440 | Babel uses the excellent [core-js](https://github.com/zloirock/core-js) as its polyfill, along with a customized [regenerator](https://github.com/facebook/regenerator) runtime for getting generators and async functions working. 441 | 442 | To include the Babel polyfill, first install it with npm: 443 | 444 | ```sh 445 | $ npm install --save babel-polyfill 446 | ``` 447 | 448 | Then simply include the polyfill at the top of any file that requires it: 449 | 450 | ```js 451 | import "babel-polyfill"; 452 | ``` 453 | 454 | ## `babel-runtime` 455 | 456 | In order to implement details of ECMAScript specs, Babel will use "helper" methods in order to keep the generated code clean. 457 | 458 | Since these helpers can get pretty long, and they get added to the top of every file you can move them into a single "runtime" which gets required. 459 | 460 | Start by installing `babel-plugin-transform-runtime` and `babel-runtime`: 461 | 462 | ```sh 463 | $ npm install --save-dev babel-plugin-transform-runtime 464 | $ npm install --save babel-runtime 465 | ``` 466 | 467 | Then update your `.babelrc`: 468 | 469 | ```diff 470 | { 471 | "plugins": [ 472 | + "transform-runtime", 473 | "transform-es2015-classes" 474 | ] 475 | } 476 | ``` 477 | 478 | Now Babel will compile code like the following: 479 | 480 | ```js 481 | class Foo { 482 | method() {} 483 | } 484 | ``` 485 | 486 | Into this: 487 | 488 | ```js 489 | import _classCallCheck from "babel-runtime/helpers/classCallCheck"; 490 | import _createClass from "babel-runtime/helpers/createClass"; 491 | 492 | let Foo = function () { 493 | function Foo() { 494 | _classCallCheck(this, Foo); 495 | } 496 | 497 | _createClass(Foo, [{ 498 | key: "method", 499 | value: function method() {} 500 | }]); 501 | 502 | return Foo; 503 | }(); 504 | ``` 505 | 506 | Rather than putting the `_classCallCheck` and `_createClass` helpers in every single file where they are needed. 507 | 508 | * * * 509 | 510 | # Babel 設定 (高度な) 511 | 512 | Most people can get by using Babel with just the built-in presets, but Babel exposes much finer-grained power than that. 513 | 514 | ## プラグインを手動で設定 515 | 516 | Babel presets are simply collections of pre-configured plugins, if you want to do something differently you manually specify plugins. This works almost exactly the same way as presets. 517 | 518 | First install a plugin: 519 | 520 | ```sh 521 | $ npm install --save-dev babel-plugin-transform-es2015-classes 522 | ``` 523 | 524 | Then add the `plugins` field to your `.babelrc`. 525 | 526 | ```diff 527 | { 528 | + "plugins": [ 529 | + "transform-es2015-classes" 530 | + ] 531 | } 532 | ``` 533 | 534 | This gives you much finer grained control over the exact transforms you are running. 535 | 536 | For a full list of official plugins see the [Babel Plugins page](http://babeljs.io/docs/plugins/). 537 | 538 | Also take a look at all the plugins that have been [built by the community](https://www.npmjs.com/search?q=babel-plugin). If you would like to learn how to write your own plugin read the [Babel Plugin Handbook](plugin-handbook.md). 539 | 540 | ## プラグインのオプション 541 | 542 | Many plugins also have options to configure them to behave differently. For example, many transforms have a "loose" mode which drops some spec behavior in favor of simpler and more performant generated code. 543 | 544 | To add options to a plugin, simply make the following change: 545 | 546 | ```diff 547 | { 548 | "plugins": [ 549 | - "transform-es2015-classes" 550 | + ["transform-es2015-classes", { "loose": true }] 551 | ] 552 | } 553 | ``` 554 | 555 | > I'll be working on updates to the plugin documentation to detail every option in the coming weeks. [Follow me for updates](https://twitter.com/thejameskyle). 556 | 557 | ## Customizing Babel based on environment 558 | 559 | Babel plugins solve many different tasks. Many of them are development tools that can help you debugging your code or integrate with tools. There are also a lot of plugins that are meant for optimizing your code in production. 560 | 561 | For this reason, it is common to want Babel configuration based on the environment. You can do this easily with your `.babelrc` file. 562 | 563 | ```diff 564 | { 565 | "presets": ["es2015"], 566 | "plugins": [], 567 | + "env": { 568 | + "development": { 569 | + "plugins": [...] 570 | + }, 571 | + "production": { 572 | + "plugins": [...] 573 | + } 574 | } 575 | } 576 | ``` 577 | 578 | Babel will enable configuration inside of `env` based on the current environment. 579 | 580 | The current environment will use `process.env.BABEL_ENV`. When `BABEL_ENV` is not available, it will fallback to `NODE_ENV`, and if that is not available it will default to `"development"`. 581 | 582 | **Unix** 583 | 584 | ```sh 585 | $ BABEL_ENV=production [COMMAND] 586 | $ NODE_ENV=production [COMMAND] 587 | ``` 588 | 589 | **Windows** 590 | 591 | ```sh 592 | $ SET BABEL_ENV=production 593 | $ [COMMAND] 594 | ``` 595 | 596 | > **Note:** `[COMMAND]` is whatever you use to run Babel (ie. `babel`, `babel-node`, or maybe just `node` if you are using the register hook). 597 | > 598 | > **Tip:** If you want your command to work across unix and windows platforms then use [`cross-env`](https://www.npmjs.com/package/cross-env). 599 | 600 | ## Making your own preset 601 | 602 | Manually specifying plugins? Plugin options? Environment-based settings? All this configuration might seem like a ton of repetition for all of your projects. 603 | 604 | For this reason, we encourage the community to create their own presets. This could be a preset for the specific [node version](https://github.com/leebenson/babel-preset-node5) you are running, or maybe a preset for your [entire](https://github.com/cloudflare/babel-preset-cf) [company](https://github.com/airbnb/babel-preset-airbnb). 605 | 606 | It's easy to create a preset. Say you have this `.babelrc` file: 607 | 608 | ```js 609 | { 610 | "presets": [ 611 | "es2015", 612 | "react" 613 | ], 614 | "plugins": [ 615 | "transform-flow-strip-types" 616 | ] 617 | } 618 | ``` 619 | 620 | All you need to do is create a new project following the naming convention `babel-preset-*` (please be responsible with this namespace), and create two files. 621 | 622 | First, create a new `package.json` file with the necessary `dependencies` for your preset. 623 | 624 | ```js 625 | { 626 | "name": "babel-preset-my-awesome-preset", 627 | "version": "1.0.0", 628 | "author": "James Kyle ", 629 | "dependencies": { 630 | "babel-preset-es2015": "^6.3.13", 631 | "babel-preset-react": "^6.3.13", 632 | "babel-plugin-transform-flow-strip-types": "^6.3.15" 633 | } 634 | } 635 | ``` 636 | 637 | Then create an `index.js` file that exports the contents of your `.babelrc` file, replacing plugin/preset strings with `require` calls. 638 | 639 | ```js 640 | module.exports = { 641 | presets: [ 642 | require("babel-preset-es2015"), 643 | require("babel-preset-react") 644 | ], 645 | plugins: [ 646 | require("babel-plugin-transform-flow-strip-types") 647 | ] 648 | }; 649 | ``` 650 | 651 | Then simply publish this to npm and you can use it like you would any preset. 652 | 653 | * * * 654 | 655 | # Babel and other tools 656 | 657 | Babel is pretty straight forward to setup once you get the hang of it, but it can be rather difficult navigating how to set it up with other tools. However, we try to work closely with other projects in order to make the experience as easy as possible. 658 | 659 | ## 静的解析ツール 660 | 661 | Newer standards bring a lot of new syntax to the language and static analysis tools are just starting to take advantage of it. 662 | 663 | ### Lint 664 | 665 | One of the most popular tools for linting is [ESLint](http://eslint.org), because of this we maintain an official [`babel-eslint`](https://github.com/babel/babel-eslint) integration. 666 | 667 | 初めに、`eslint` と`babel-eslint`をインストールします. 668 | 669 | ```sh 670 | $ npm install --save-dev eslint babel-eslint 671 | ``` 672 | 673 | Next create or use the existing `.eslintrc` file in your project and set the `parser` as `babel-eslint`. 674 | 675 | ```diff 676 | { 677 | + "parser": "babel-eslint", 678 | "rules": { 679 | ... 680 | } 681 | } 682 | ``` 683 | 684 | Now add a `lint` task to your npm `package.json` scripts: 685 | 686 | ```diff 687 | { 688 | "name": "my-module", 689 | "scripts": { 690 | + "lint": "eslint my-files.js" 691 | }, 692 | "devDependencies": { 693 | "babel-eslint": "...", 694 | "eslint": "..." 695 | } 696 | } 697 | ``` 698 | 699 | Then just run the task and you will be all setup. 700 | 701 | ```sh 702 | $ npm run lint 703 | ``` 704 | 705 | For more information consult the [`babel-eslint`](https://github.com/babel/babel-eslint) or [`eslint`](http://eslint.org) documentation. 706 | 707 | ### Code Style 708 | 709 | > JSCS has merged with ESLint, so checkout Code Styling with ESLint. 710 | 711 | JSCS is an extremely popular tool for taking linting a step further into checking the style of the code itself. A core maintainer of both the Babel and JSCS projects ([@hzoo](https://github.com/hzoo)) maintains an official integration with JSCS. 712 | 713 | Even better, this integration now lives within JSCS itself under the `--esnext` option. So integrating Babel is as easy as: 714 | 715 | $ jscs . --esnext 716 | 717 | 718 | From the cli, or adding the `esnext` option to your `.jscsrc` file. 719 | 720 | ```diff 721 | { 722 | "preset": "airbnb", 723 | + "esnext": true 724 | } 725 | ``` 726 | 727 | For more information consult the [`babel-jscs`](https://github.com/jscs-dev/babel-jscs) or [`jscs`](http://jscs.info) documentation. 728 | 729 | 734 | 735 | ### Documentation 736 | 737 | Using Babel, ES2015, and Flow you can infer a lot about your code. Using [documentation.js](http://documentation.js.org) you can generate detailed API documentation very easily. 738 | 739 | Documentation.js uses Babel behind the scenes to support all of the latest syntax including Flow annotations in order to declare the types in your code. 740 | 741 | ## フレームワーク 742 | 743 | All of the major JavaScript frameworks are now focused on aligning their APIs around the future of the language. Because of this, there has been a lot of work going into the tooling. 744 | 745 | Frameworks have the opportunity not just to use Babel but to extend it in ways that improve their users' experience. 746 | 747 | ### React 748 | 749 | React has dramatically changed their API to align with ES2015 classes ([Read about the updated API here](https://babeljs.io/blog/2015/06/07/react-on-es6-plus)). Even further, React relies on Babel to compile it's JSX syntax, deprecating it's own custom tooling in favor of Babel. You can start by setting up the `babel-preset-react` package following the [instructions above](#babel-preset-react). 750 | 751 | The React community took Babel and ran with it. There are now a number of transforms [built by the community](https://www.npmjs.com/search?q=babel-plugin+react). 752 | 753 | Most notably the [`babel-plugin-react-transform`](https://github.com/gaearon/babel-plugin-react-transform) plugin which combined with a number of [React-specific transforms](https://github.com/gaearon/babel-plugin-react-transform#transforms) can enable things like *hot module reloading* and other debugging utilities. 754 | 755 | 760 | 761 | ## テキストエディタ・IDE 762 | 763 | Introducing ES2015, JSX, and Flow syntax with Babel can be helpful, but if your text editor doesn't support it then it can be a really bad experience. For this reason you will want to setup your text editor or IDE with a Babel plugin. 764 | 765 | * [Sublime Text](https://github.com/babel/babel-sublime) 766 | * [Atom](https://atom.io/packages/language-babel) 767 | * [Vim](https://github.com/jbgutierrez/vim-babel) 768 | * [WebStorm](https://babeljs.io/docs/setup/#webstorm) 769 | 770 | 775 | 776 | * * * 777 | 778 | # Babel のサポート 779 | 780 | Babel has a very large and quickly growing community, as we grow we want to ensure that people have all the resources they need to be successful. So we provide a number of different channels for getting support. 781 | 782 | Remember that across all of these communities we enforce a [Code of Conduct](https://github.com/babel/babel/blob/master/CODE_OF_CONDUCT.md). If you break the Code of Conduct, action will be taken. So please read it and be conscious of it when interacting with others. 783 | 784 | We are also looking to grow a self-supporting community, for people who stick around and support others. If you find someone asking a question you know the answer to, take a few minutes and help them out. Try your best to be kind and understanding when doing so. 785 | 786 | ## Babel Forum 787 | 788 | [Discourse](http://www.discourse.org) has provided us with a hosted version of their forum software for free (and we love them for it!). If forums are your thing please stop by [discuss.babeljs.io](https://discuss.babeljs.io). 789 | 790 | ## Babel Chat 791 | 792 | Everyone loves [Slack](https://slack.com). If you're looking for immediate support from the community then come chat with us at [slack.babeljs.io](https://slack.babeljs.io). 793 | 794 | 799 | 800 | ## Babel Issues 801 | 802 | Babel uses the issue tracker provided by [Github](http://github.com). 803 | 804 | You can see all the open and closed issues on [Github](https://github.com/babel/babel/issues). 805 | 806 | If you want to open a new issue: 807 | 808 | * [Search for an existing issue](https://github.com/babel/babel/issues) 809 | * [Create a new bug report](https://github.com/babel/babel/issues/new) or [request a new feature](https://github.com/babel/babel/issues/new) 810 | 811 | ### Creating an awesome Babel bug report 812 | 813 | Babel issues can sometimes be very difficult to debug remotely, so we need all the help we can get. Spending a few more minutes crafting a really nice bug report can help get your problem solved significantly faster. 814 | 815 | First, try isolating your problem. It's extremely unlikely that every part of your setup is contributing to the problem. If your problem is a piece of input code, try deleting as much code as possible that still causes an issue. 816 | 817 | > [WIP] 818 | 819 | * * * 820 | 821 | > ***最新の情報を受け取るには、Twitterで[@thejameskyle](https://twitter.com/thejameskyle)をフォローしてください。*** -------------------------------------------------------------------------------- /translations/fi/user-handbook.md: -------------------------------------------------------------------------------- 1 | # Babel User Handbook 2 | 3 | This document covers everything you ever wanted to know about using [Babel](https://babeljs.io) and related tooling. 4 | 5 | [![cc-by-4.0](https://licensebuttons.net/l/by/4.0/80x15.png)](http://creativecommons.org/licenses/by/4.0/) 6 | 7 | Ohje löytyy myös muille kielille, kts. [README](/README.md) (näet koko luettelon). 8 | 9 | # Sisällysluettelo 10 | 11 | * [Johdanto](#toc-introduction) 12 | * [Setting up Babel](#toc-setting-up-babel) 13 | * [`babel-cli`](#toc-babel-cli) 14 | * [Running Babel CLI from within a project](#toc-running-babel-cli-from-within-a-project) 15 | * [`babel-register`](#toc-babel-register) 16 | * [`babel-node`](#toc-babel-node) 17 | * [`babel-core`](#toc-babel-core) 18 | * [Configuring Babel](#toc-configuring-babel) 19 | * [`.babelrc`](#toc-babelrc) 20 | * [`babel-preset-es2015`](#toc-babel-preset-es2015) 21 | * [`babel-preset-react`](#toc-babel-preset-react) 22 | * [`babel-preset-stage-x`](#toc-babel-preset-stage-x) 23 | * [Executing Babel-generated code](#toc-executing-babel-generated-code) 24 | * [`babel-polyfill`](#toc-babel-polyfill) 25 | * [`babel-runtime`](#toc-babel-runtime) 26 | * [Configuring Babel (Advanced)](#toc-configuring-babel-advanced) 27 | * [Manually specifying plugins](#toc-manually-specifying-plugins) 28 | * [Plugin options](#toc-plugin-options) 29 | * [Customizing Babel based on environment](#toc-customizing-babel-based-on-environment) 30 | * [Making your own preset](#toc-making-your-own-preset) 31 | * [Babel and other tools](#toc-babel-and-other-tools) 32 | * [Static analysis tools](#toc-static-analysis-tools) 33 | * [Linting](#toc-linting) 34 | * [Code Style](#toc-code-style) 35 | * [Documentation](#toc-documentation) 36 | * [Frameworks](#toc-frameworks) 37 | * [React](#toc-react) 38 | * [Text Editors and IDEs](#toc-text-editors-and-ides) 39 | * [Babel Support](#toc-babel-support) 40 | * [Babel Forum](#toc-babel-forum) 41 | * [Babel Chat](#toc-babel-chat) 42 | * [Babel Issues](#toc-babel-issues) 43 | * [Creating an awesome Babel bug report](#toc-creating-an-awesome-babel-bug-report) 44 | 45 | # Johdanto 46 | 47 | Babel on geneerinen ja monikäyttöinen kääntäjä JavaScriptille. Babelin avulla voit käyttää (ja luoda) seuraavan sukupolven Javascript-koodia ja sitä tukevia apuohjelmia. 48 | 49 | JavaScript uudistuu kielenä jatkuvasti, niin standardien, ehdotettujen ominaisuuksien kuin uusien ominaisuuksien toteutuksen myötä. Babel mahdollistaa uusimpien ominaisuuksien käyttöönoton vuosia ennen niiden ilmestymistä selaimiin. 50 | 51 | Babel mahdollistaa tämän kääntämällä upouuden JavaScriptin sellaiseksi versioksi, joka toimii kaikkialla. Tällaistä käännöstä kutsutaan lähdekielestä toiseen kääntämiseksi, tai termillä 'transpiling'. 52 | 53 | For example, Babel could transform the new ES2015 arrow function syntax from this: 54 | 55 | ```js 56 | const square = n => n * n; 57 | ``` 58 | 59 | Into the following: 60 | 61 | ```js 62 | const square = function square(n) { 63 | return n * n; 64 | }; 65 | ``` 66 | 67 | However, Babel can do much more than this as Babel has support for syntax extensions such as the JSX syntax for React and Flow syntax support for static type checking. 68 | 69 | Further than that, everything in Babel is simply a plugin and anyone can go out and create their own plugins using the full power of Babel to do whatever they want. 70 | 71 | *Even further* than that, Babel is broken down into a number of core modules that anyone can use to build the next generation of JavaScript tooling. 72 | 73 | Many people do too, the ecosystem that has sprung up around Babel is massive and very diverse. Throughout this handbook I'll be covering both how built-in Babel tools work as well as some useful things from around the community. 74 | 75 | > ***Jos haluat pysyä ajantasalla, seuraa Twitterissä: [@thejameskyle](https://twitter.com/thejameskyle).*** 76 | 77 | * * * 78 | 79 | # Setting up Babel 80 | 81 | Koska JavaScript -yhteisöllä ei ole mitään "ainoaa ja oikeaa" kääntäjää, sovelluskehikkoa, alustaa, jne., Babelista on viralliset integroinnit kaikkiin suurimpiin työkaluihin. Olipa käytössäsi Gulp, Browserify, Ember, Meteor tai jotain noiden väliltä, voit odottaa silti löytäväsi virallisen integroinnin Babeliin. 82 | 83 | Tässä perehdymme vain Babelin sisäänrakennettuihin asennusmahdollisuuksiin, mutta voit halutessasi käydä [asennusohjesivulla](http://babeljs.io/docs/setup) tutustumassa kaikkiin vaihtoehtoihin. 84 | 85 | > **Huom!** Oppaassa oletetaan että tunnet komentorivityökalut kuten `node` ja `npm`. Tutustu näihin ennen kuin jatkat lukemista. 86 | 87 | ## `babel-cli` 88 | 89 | Babel CLI tarjoaa yksinkertaisen tavan kääntää JS-tiedostoja komentoriviltä. 90 | 91 | Asennetaan ensin babel-cli globaalisti. 92 | 93 | ```sh 94 | $ npm install --global babel-cli 95 | ``` 96 | 97 | Nyt voimme kääntää kokeeksi: 98 | 99 | ```sh 100 | $ babel my-file.js 101 | ``` 102 | 103 | Babel tulostaa käännetyn koodin terminaaliin. Jos haluat sen menevän tiedostoon, anna parametri `--out-file` tai `-o`. 104 | 105 | ```sh 106 | $ babel example.js --out-file compiled.js 107 | # tai 108 | $ babel example.js -o compiled.js 109 | ``` 110 | 111 | Jos haluamme kääntää koko hakemiston sisällön uuteen hakemistoon, voimme tehdä sen parametrilla `-out-dir` tai `-d`. 112 | 113 | ```sh 114 | $ babel src --out-dir lib 115 | # or 116 | $ babel src -d lib 117 | ``` 118 | 119 | ### Babel CLI :n käyttö projektikansiosta 120 | 121 | Vaikka Babel CLI *voidaan* asentaa globaalisti (-g), se kannattaa asentaa **paikallisesti** aina kulloisenkin projektin yhteyteen. 122 | 123 | Paikallisella asennuksella on kaksi etua. 124 | 125 | 1. Samalla koneella voi olla projekteja, jotka haluavat tietyn Babel -version, jolloin voit päivittää niitä erikseen (paikallisesti). 126 | 2. Projektisi ei enää riipu omasta työympäristöstäsi. Se tekee projektistasi helpommin siirrettävän ja helpomman asentaa. 127 | 128 | Voimme asentaa Babel CLI paikallisesti antamalla: 129 | 130 | ```sh 131 | $ npm install --save-dev babel-cli 132 | ``` 133 | 134 | > **Huom:** Koska Babelin suoritus koneen globaalista versiosta on huono idea, voit varmuuden vuoksi poistaa globaalin asennuksen: 135 | > 136 | > ```sh 137 | $ npm uninstall --global babel-cli 138 | ``` 139 | 140 | After that finishes installing, your `package.json` file should look like this: 141 | 142 | ```json 143 | { 144 | "name": "my-project", 145 | "version": "1.0.0", 146 | "devDependencies": { 147 | "babel-cli": "^6.0.0" 148 | } 149 | } 150 | ``` 151 | 152 | Now instead of running Babel directly from the command line we're going to put our commands in **npm scripts** which will use our local version. 153 | 154 | Simply add a `"scripts"` field to your `package.json` and put the babel command inside there as `build`. 155 | 156 | ```diff 157 | { 158 | "name": "my-project", 159 | "version": "1.0.0", 160 | + "scripts": { 161 | + "build": "babel src -d lib" 162 | + }, 163 | "devDependencies": { 164 | "babel-cli": "^6.0.0" 165 | } 166 | } 167 | ``` 168 | 169 | Now from our terminal we can run: 170 | 171 | ```js 172 | npm run build 173 | ``` 174 | 175 | This will run Babel the same way as before, only now we are using a local copy. 176 | 177 | ## `babel-register` 178 | 179 | The next most common method of running Babel is through `babel-register`. This option will allow you to run Babel just by requiring files, which may integrate with your setup better. 180 | 181 | Note that this is not meant for production use. It's considered bad practice to deploy code that gets compiled this way. It is far better to compile ahead of time before deploying. However this works quite well for build scripts or other things that you run locally. 182 | 183 | First let's create an `index.js` file in our project. 184 | 185 | ```js 186 | console.log("Hello world!"); 187 | ``` 188 | 189 | If we were to run this with `node index.js` this wouldn't be compiled with Babel. So instead of doing that, we'll setup `babel-register`. 190 | 191 | First install `babel-register`. 192 | 193 | ```sh 194 | $ npm install --save-dev babel-register 195 | ``` 196 | 197 | Next, create a `register.js` file in the project and write the following code: 198 | 199 | ```js 200 | require("babel-register"); 201 | require("./index.js"); 202 | ``` 203 | 204 | What this does is *registers* Babel in Node's module system and begins compiling every file that is `require`'d. 205 | 206 | Now, instead of running `node index.js` we can use `register.js` instead. 207 | 208 | ```sh 209 | $ node register.js 210 | ``` 211 | 212 | > **Note:** You can't register Babel in the same file that you want to compile. As node is executing the file before Babel has a chance to compile it. 213 | > 214 | > ```js 215 | require("babel-register"); 216 | // not compiled: 217 | console.log("Hello world!"); 218 | ``` 219 | 220 | ## `babel-node` 221 | 222 | If you are just running some code via the `node` CLI the easiest way to integrate Babel might be to use the `babel-node` CLI which largely is just a drop in replacement for the `node` CLI. 223 | 224 | Note that this is not meant for production use. It's considered bad practice to deploy code that gets compiled this way. It is far better to compile ahead of time before deploying. However this works quite well for build scripts or other things that you run locally. 225 | 226 | First make sure that you have `babel-cli` installed. 227 | 228 | ```sh 229 | $ npm install --save-dev babel-cli 230 | ``` 231 | 232 | > **Note:** If you are wondering why we are installing this locally, please read the [Running Babel CLI from within a project](#toc-running-babel-cli-from-within-a-project) section above. 233 | 234 | Then replace wherever you are running `node` with `babel-node`. 235 | 236 | If you are using npm `scripts` you can simply do: 237 | 238 | ```diff 239 | { 240 | "scripts": { 241 | - "script-name": "node script.js" 242 | + "script-name": "babel-node script.js" 243 | } 244 | } 245 | ``` 246 | 247 | Otherwise you'll need to write out the path to `babel-node` itself. 248 | 249 | ```diff 250 | - node script.js 251 | + ./node_modules/.bin/babel-node script.js 252 | ``` 253 | 254 | > Tip: You can also use [`npm-run`](https://www.npmjs.com/package/npm-run). 255 | 256 | ## `babel-core` 257 | 258 | If you need to use Babel programmatically for some reason, you can use the `babel-core` package itself. 259 | 260 | First install `babel-core`. 261 | 262 | ```sh 263 | $ npm install babel-core 264 | ``` 265 | 266 | ```js 267 | var babel = require("babel-core"); 268 | ``` 269 | 270 | If you have a string of JavaScript you can compile it directly using `babel.transform`. 271 | 272 | ```js 273 | babel.transform("code();", options); 274 | // => { code, map, ast } 275 | ``` 276 | 277 | If you are working with files you can use either the asynchronous api: 278 | 279 | ```js 280 | babel.transformFile("filename.js", options, function(err, result) { 281 | result; // => { code, map, ast } 282 | }); 283 | ``` 284 | 285 | Or the synchronous api: 286 | 287 | ```js 288 | babel.transformFileSync("filename.js", options); 289 | // => { code, map, ast } 290 | ``` 291 | 292 | If you already have a Babel AST for whatever reason you may transform from the AST directly. 293 | 294 | ```js 295 | babel.transformFromAst(ast, code, options); 296 | // => { code, map, ast } 297 | ``` 298 | 299 | For all of the above methods, `options` refers to https://babeljs.io/docs/usage/api/#options. 300 | 301 | * * * 302 | 303 | # Configuring Babel 304 | 305 | You may have noticed by now that running Babel on its own doesn't seem to do anything other than copy JavaScript files from one location to another. 306 | 307 | This is because we haven't told Babel to do anything yet. 308 | 309 | > Since Babel is a general purpose compiler that gets used in a myriad of different ways, it doesn't do anything by default. You have to explicitly tell Babel what it should be doing. 310 | 311 | You can give Babel instructions on what to do by installing **plugins** or **presets** (groups of plugins). 312 | 313 | ## `.babelrc` 314 | 315 | Before we start telling Babel what to do. We need to create a configuration file. All you need to do is create a `.babelrc` file at the root of your project. Start off with it like this: 316 | 317 | ```js 318 | { 319 | "presets": [], 320 | "plugins": [] 321 | } 322 | ``` 323 | 324 | This file is how you configure Babel to do what you want. 325 | 326 | > **Note:** While you can also pass options to Babel in other ways the `.babelrc` file is convention and is the best way. 327 | 328 | ## `babel-preset-es2015` 329 | 330 | Let's start by telling Babel to compile ES2015 (the newest version of the JavaScript standard, also known as ES6) to ES5 (the version available in most JavaScript environments today). 331 | 332 | We'll do this by installing the "es2015" Babel preset: 333 | 334 | ```sh 335 | $ npm install --save-dev babel-preset-es2015 336 | ``` 337 | 338 | Next we'll modify our `.babelrc` to include that preset. 339 | 340 | ```diff 341 | { 342 | "presets": [ 343 | + "es2015" 344 | ], 345 | "plugins": [] 346 | } 347 | ``` 348 | 349 | ## `babel-preset-react` 350 | 351 | Setting up React is just as easy. Just install the preset: 352 | 353 | ```sh 354 | $ npm install --save-dev babel-preset-react 355 | ``` 356 | 357 | Then add the preset to your `.babelrc` file: 358 | 359 | ```diff 360 | { 361 | "presets": [ 362 | "es2015", 363 | + "react" 364 | ], 365 | "plugins": [] 366 | } 367 | ``` 368 | 369 | ## `babel-preset-stage-x` 370 | 371 | JavaScript also has some proposals that are making their way into the standard through the TC39's (the technical committee behind the ECMAScript standard) process. 372 | 373 | This process is broken through a 5 stage (0-4) process. As proposals gain more traction and are more likely to be accepted into the standard they proceed through the various stages, finally being accepted into the standard at stage 4. 374 | 375 | These are bundled in babel as 4 different presets: 376 | 377 | * `babel-preset-stage-0` 378 | * `babel-preset-stage-1` 379 | * `babel-preset-stage-2` 380 | * `babel-preset-stage-3` 381 | 382 | > Note that there is no stage-4 preset as it is simply the `es2015` preset above. 383 | 384 | Each of these presets requires the preset for the later stages. i.e. `babel-preset-stage-1` requires `babel-preset-stage-2` which requires `babel-preset-stage-3`. 385 | 386 | Simply install the stage you are interested in using: 387 | 388 | ```sh 389 | $ npm install --save-dev babel-preset-stage-2 390 | ``` 391 | 392 | Then you can add it to your `.babelrc` config. 393 | 394 | ```diff 395 | { 396 | "presets": [ 397 | "es2015", 398 | "react", 399 | + "stage-2" 400 | ], 401 | "plugins": [] 402 | } 403 | ``` 404 | 405 | * * * 406 | 407 | # Executing Babel-generated code 408 | 409 | So you've compiled your code with Babel, but this is not the end of the story. 410 | 411 | ## `babel-polyfill` 412 | 413 | Almost all futuristic JavaScript syntax can be compiled with Babel, but the same is not true for APIs. 414 | 415 | For example, the following code has an arrow function that needs to be compiled: 416 | 417 | ```js 418 | function addAll() { 419 | return Array.from(arguments).reduce((a, b) => a + b); 420 | } 421 | ``` 422 | 423 | Which turns into this: 424 | 425 | ```js 426 | function addAll() { 427 | return Array.from(arguments).reduce(function(a, b) { 428 | return a + b; 429 | }); 430 | } 431 | ``` 432 | 433 | However, this still won't work everywhere because `Array.from` doesn't exist in every JavaScript environment. 434 | 435 | Uncaught TypeError: Array.from is not a function 436 | 437 | 438 | To solve this problem we use something called a [Polyfill](https://remysharp.com/2010/10/08/what-is-a-polyfill). Simply put, a polyfill is a piece of code that replicates a native api that does not exist in the current runtime. Allowing you to use APIs such as `Array.from` before they are available. 439 | 440 | Babel uses the excellent [core-js](https://github.com/zloirock/core-js) as its polyfill, along with a customized [regenerator](https://github.com/facebook/regenerator) runtime for getting generators and async functions working. 441 | 442 | To include the Babel polyfill, first install it with npm: 443 | 444 | ```sh 445 | $ npm install --save babel-polyfill 446 | ``` 447 | 448 | Then simply include the polyfill at the top of any file that requires it: 449 | 450 | ```js 451 | import "babel-polyfill"; 452 | ``` 453 | 454 | ## `babel-runtime` 455 | 456 | In order to implement details of ECMAScript specs, Babel will use "helper" methods in order to keep the generated code clean. 457 | 458 | Since these helpers can get pretty long, and they get added to the top of every file you can move them into a single "runtime" which gets required. 459 | 460 | Start by installing `babel-plugin-transform-runtime` and `babel-runtime`: 461 | 462 | ```sh 463 | $ npm install --save-dev babel-plugin-transform-runtime 464 | $ npm install --save babel-runtime 465 | ``` 466 | 467 | Then update your `.babelrc`: 468 | 469 | ```diff 470 | { 471 | "plugins": [ 472 | + "transform-runtime", 473 | "transform-es2015-classes" 474 | ] 475 | } 476 | ``` 477 | 478 | Now Babel will compile code like the following: 479 | 480 | ```js 481 | class Foo { 482 | method() {} 483 | } 484 | ``` 485 | 486 | Into this: 487 | 488 | ```js 489 | import _classCallCheck from "babel-runtime/helpers/classCallCheck"; 490 | import _createClass from "babel-runtime/helpers/createClass"; 491 | 492 | let Foo = function () { 493 | function Foo() { 494 | _classCallCheck(this, Foo); 495 | } 496 | 497 | _createClass(Foo, [{ 498 | key: "method", 499 | value: function method() {} 500 | }]); 501 | 502 | return Foo; 503 | }(); 504 | ``` 505 | 506 | Rather than putting the `_classCallCheck` and `_createClass` helpers in every single file where they are needed. 507 | 508 | * * * 509 | 510 | # Configuring Babel (Advanced) 511 | 512 | Most people can get by using Babel with just the built-in presets, but Babel exposes much finer-grained power than that. 513 | 514 | ## Manually specifying plugins 515 | 516 | Babel presets are simply collections of pre-configured plugins, if you want to do something differently you manually specify plugins. This works almost exactly the same way as presets. 517 | 518 | First install a plugin: 519 | 520 | ```sh 521 | $ npm install --save-dev babel-plugin-transform-es2015-classes 522 | ``` 523 | 524 | Then add the `plugins` field to your `.babelrc`. 525 | 526 | ```diff 527 | { 528 | + "plugins": [ 529 | + "transform-es2015-classes" 530 | + ] 531 | } 532 | ``` 533 | 534 | This gives you much finer grained control over the exact transforms you are running. 535 | 536 | For a full list of official plugins see the [Babel Plugins page](http://babeljs.io/docs/plugins/). 537 | 538 | Also take a look at all the plugins that have been [built by the community](https://www.npmjs.com/search?q=babel-plugin). If you would like to learn how to write your own plugin read the [Babel Plugin Handbook](plugin-handbook.md). 539 | 540 | ## Plugin options 541 | 542 | Many plugins also have options to configure them to behave differently. For example, many transforms have a "loose" mode which drops some spec behavior in favor of simpler and more performant generated code. 543 | 544 | To add options to a plugin, simply make the following change: 545 | 546 | ```diff 547 | { 548 | "plugins": [ 549 | - "transform-es2015-classes" 550 | + ["transform-es2015-classes", { "loose": true }] 551 | ] 552 | } 553 | ``` 554 | 555 | > I'll be working on updates to the plugin documentation to detail every option in the coming weeks. [Follow me for updates](https://twitter.com/thejameskyle). 556 | 557 | ## Customizing Babel based on environment 558 | 559 | Babel plugins solve many different tasks. Many of them are development tools that can help you debugging your code or integrate with tools. There are also a lot of plugins that are meant for optimizing your code in production. 560 | 561 | For this reason, it is common to want Babel configuration based on the environment. You can do this easily with your `.babelrc` file. 562 | 563 | ```diff 564 | { 565 | "presets": ["es2015"], 566 | "plugins": [], 567 | + "env": { 568 | + "development": { 569 | + "plugins": [...] 570 | + }, 571 | + "production": { 572 | + "plugins": [...] 573 | + } 574 | } 575 | } 576 | ``` 577 | 578 | Babel will enable configuration inside of `env` based on the current environment. 579 | 580 | The current environment will use `process.env.BABEL_ENV`. When `BABEL_ENV` is not available, it will fallback to `NODE_ENV`, and if that is not available it will default to `"development"`. 581 | 582 | **Unix** 583 | 584 | ```sh 585 | $ BABEL_ENV=production [COMMAND] 586 | $ NODE_ENV=production [COMMAND] 587 | ``` 588 | 589 | **Windows** 590 | 591 | ```sh 592 | $ SET BABEL_ENV=production 593 | $ [COMMAND] 594 | ``` 595 | 596 | > **Note:** `[COMMAND]` is whatever you use to run Babel (ie. `babel`, `babel-node`, or maybe just `node` if you are using the register hook). 597 | > 598 | > **Tip:** If you want your command to work across unix and windows platforms then use [`cross-env`](https://www.npmjs.com/package/cross-env). 599 | 600 | ## Making your own preset 601 | 602 | Manually specifying plugins? Plugin options? Environment-based settings? All this configuration might seem like a ton of repetition for all of your projects. 603 | 604 | For this reason, we encourage the community to create their own presets. This could be a preset for the specific [node version](https://github.com/leebenson/babel-preset-node5) you are running, or maybe a preset for your [entire](https://github.com/cloudflare/babel-preset-cf) [company](https://github.com/airbnb/babel-preset-airbnb). 605 | 606 | It's easy to create a preset. Say you have this `.babelrc` file: 607 | 608 | ```js 609 | { 610 | "presets": [ 611 | "es2015", 612 | "react" 613 | ], 614 | "plugins": [ 615 | "transform-flow-strip-types" 616 | ] 617 | } 618 | ``` 619 | 620 | All you need to do is create a new project following the naming convention `babel-preset-*` (please be responsible with this namespace), and create two files. 621 | 622 | First, create a new `package.json` file with the necessary `dependencies` for your preset. 623 | 624 | ```js 625 | { 626 | "name": "babel-preset-my-awesome-preset", 627 | "version": "1.0.0", 628 | "author": "James Kyle ", 629 | "dependencies": { 630 | "babel-preset-es2015": "^6.3.13", 631 | "babel-preset-react": "^6.3.13", 632 | "babel-plugin-transform-flow-strip-types": "^6.3.15" 633 | } 634 | } 635 | ``` 636 | 637 | Then create an `index.js` file that exports the contents of your `.babelrc` file, replacing plugin/preset strings with `require` calls. 638 | 639 | ```js 640 | module.exports = { 641 | presets: [ 642 | require("babel-preset-es2015"), 643 | require("babel-preset-react") 644 | ], 645 | plugins: [ 646 | require("babel-plugin-transform-flow-strip-types") 647 | ] 648 | }; 649 | ``` 650 | 651 | Then simply publish this to npm and you can use it like you would any preset. 652 | 653 | * * * 654 | 655 | # Babel and other tools 656 | 657 | Babel is pretty straight forward to setup once you get the hang of it, but it can be rather difficult navigating how to set it up with other tools. However, we try to work closely with other projects in order to make the experience as easy as possible. 658 | 659 | ## Static analysis tools 660 | 661 | Newer standards bring a lot of new syntax to the language and static analysis tools are just starting to take advantage of it. 662 | 663 | ### Linting 664 | 665 | One of the most popular tools for linting is [ESLint](http://eslint.org), because of this we maintain an official [`babel-eslint`](https://github.com/babel/babel-eslint) integration. 666 | 667 | First install `eslint` and `babel-eslint`. 668 | 669 | ```sh 670 | $ npm install --save-dev eslint babel-eslint 671 | ``` 672 | 673 | Next create or use the existing `.eslintrc` file in your project and set the `parser` as `babel-eslint`. 674 | 675 | ```diff 676 | { 677 | + "parser": "babel-eslint", 678 | "rules": { 679 | ... 680 | } 681 | } 682 | ``` 683 | 684 | Now add a `lint` task to your npm `package.json` scripts: 685 | 686 | ```diff 687 | { 688 | "name": "my-module", 689 | "scripts": { 690 | + "lint": "eslint my-files.js" 691 | }, 692 | "devDependencies": { 693 | "babel-eslint": "...", 694 | "eslint": "..." 695 | } 696 | } 697 | ``` 698 | 699 | Then just run the task and you will be all setup. 700 | 701 | ```sh 702 | $ npm run lint 703 | ``` 704 | 705 | For more information consult the [`babel-eslint`](https://github.com/babel/babel-eslint) or [`eslint`](http://eslint.org) documentation. 706 | 707 | ### Code Style 708 | 709 | > JSCS has merged with ESLint, so checkout Code Styling with ESLint. 710 | 711 | JSCS is an extremely popular tool for taking linting a step further into checking the style of the code itself. A core maintainer of both the Babel and JSCS projects ([@hzoo](https://github.com/hzoo)) maintains an official integration with JSCS. 712 | 713 | Even better, this integration now lives within JSCS itself under the `--esnext` option. So integrating Babel is as easy as: 714 | 715 | $ jscs . --esnext 716 | 717 | 718 | From the cli, or adding the `esnext` option to your `.jscsrc` file. 719 | 720 | ```diff 721 | { 722 | "preset": "airbnb", 723 | + "esnext": true 724 | } 725 | ``` 726 | 727 | For more information consult the [`babel-jscs`](https://github.com/jscs-dev/babel-jscs) or [`jscs`](http://jscs.info) documentation. 728 | 729 | 734 | 735 | ### Documentation 736 | 737 | Using Babel, ES2015, and Flow you can infer a lot about your code. Using [documentation.js](http://documentation.js.org) you can generate detailed API documentation very easily. 738 | 739 | Documentation.js uses Babel behind the scenes to support all of the latest syntax including Flow annotations in order to declare the types in your code. 740 | 741 | ## Frameworks 742 | 743 | All of the major JavaScript frameworks are now focused on aligning their APIs around the future of the language. Because of this, there has been a lot of work going into the tooling. 744 | 745 | Frameworks have the opportunity not just to use Babel but to extend it in ways that improve their users' experience. 746 | 747 | ### React 748 | 749 | React has dramatically changed their API to align with ES2015 classes ([Read about the updated API here](https://babeljs.io/blog/2015/06/07/react-on-es6-plus)). Even further, React relies on Babel to compile it's JSX syntax, deprecating it's own custom tooling in favor of Babel. You can start by setting up the `babel-preset-react` package following the [instructions above](#babel-preset-react). 750 | 751 | The React community took Babel and ran with it. There are now a number of transforms [built by the community](https://www.npmjs.com/search?q=babel-plugin+react). 752 | 753 | Most notably the [`babel-plugin-react-transform`](https://github.com/gaearon/babel-plugin-react-transform) plugin which combined with a number of [React-specific transforms](https://github.com/gaearon/babel-plugin-react-transform#transforms) can enable things like *hot module reloading* and other debugging utilities. 754 | 755 | 760 | 761 | ## Text Editors and IDEs 762 | 763 | Introducing ES2015, JSX, and Flow syntax with Babel can be helpful, but if your text editor doesn't support it then it can be a really bad experience. For this reason you will want to setup your text editor or IDE with a Babel plugin. 764 | 765 | * [Sublime Text](https://github.com/babel/babel-sublime) 766 | * [Atom](https://atom.io/packages/language-babel) 767 | * [Vim](https://github.com/jbgutierrez/vim-babel) 768 | * [WebStorm](https://babeljs.io/docs/setup/#webstorm) 769 | 770 | 775 | 776 | * * * 777 | 778 | # Babel Support 779 | 780 | Babel has a very large and quickly growing community, as we grow we want to ensure that people have all the resources they need to be successful. So we provide a number of different channels for getting support. 781 | 782 | Remember that across all of these communities we enforce a [Code of Conduct](https://github.com/babel/babel/blob/master/CODE_OF_CONDUCT.md). If you break the Code of Conduct, action will be taken. So please read it and be conscious of it when interacting with others. 783 | 784 | We are also looking to grow a self-supporting community, for people who stick around and support others. If you find someone asking a question you know the answer to, take a few minutes and help them out. Try your best to be kind and understanding when doing so. 785 | 786 | ## Babel Forum 787 | 788 | [Discourse](http://www.discourse.org) has provided us with a hosted version of their forum software for free (and we love them for it!). If forums are your thing please stop by [discuss.babeljs.io](https://discuss.babeljs.io). 789 | 790 | ## Babel Chat 791 | 792 | Everyone loves [Slack](https://slack.com). If you're looking for immediate support from the community then come chat with us at [slack.babeljs.io](https://slack.babeljs.io). 793 | 794 | 799 | 800 | ## Babel Issues 801 | 802 | Babel uses the issue tracker provided by [Github](http://github.com). 803 | 804 | You can see all the open and closed issues on [Github](https://github.com/babel/babel/issues). 805 | 806 | If you want to open a new issue: 807 | 808 | * [Search for an existing issue](https://github.com/babel/babel/issues) 809 | * [Create a new bug report](https://github.com/babel/babel/issues/new) or [request a new feature](https://github.com/babel/babel/issues/new) 810 | 811 | ### Creating an awesome Babel bug report 812 | 813 | Babel issues can sometimes be very difficult to debug remotely, so we need all the help we can get. Spending a few more minutes crafting a really nice bug report can help get your problem solved significantly faster. 814 | 815 | First, try isolating your problem. It's extremely unlikely that every part of your setup is contributing to the problem. If your problem is a piece of input code, try deleting as much code as possible that still causes an issue. 816 | 817 | > [WIP] 818 | 819 | * * * 820 | 821 | > ***Jos haluat pysyä ajantasalla, seuraa Twitterissä: [@thejameskyle](https://twitter.com/thejameskyle).*** -------------------------------------------------------------------------------- /translations/cs/user-handbook.md: -------------------------------------------------------------------------------- 1 | # Babel User Handbook 2 | 3 | This document covers everything you ever wanted to know about using [Babel](https://babeljs.io) and related tooling. 4 | 5 | [![cc-by-4.0](https://licensebuttons.net/l/by/4.0/80x15.png)](http://creativecommons.org/licenses/by/4.0/) 6 | 7 | Tato příručka je k dispozici i v dalších jazycích, úplný seznam naleznete v [souboru README](/README.md). 8 | 9 | # Obsah 10 | 11 | * [Úvod](#toc-introduction) 12 | * [Setting up Babel](#toc-setting-up-babel) 13 | * [`babel-cli`](#toc-babel-cli) 14 | * [Running Babel CLI from within a project](#toc-running-babel-cli-from-within-a-project) 15 | * [`babel-register`](#toc-babel-register) 16 | * [`babel-node`](#toc-babel-node) 17 | * [`babel-core`](#toc-babel-core) 18 | * [Configuring Babel](#toc-configuring-babel) 19 | * [`.babelrc`](#toc-babelrc) 20 | * [`babel-preset-es2015`](#toc-babel-preset-es2015) 21 | * [`babel-preset-react`](#toc-babel-preset-react) 22 | * [`babel-preset-stage-x`](#toc-babel-preset-stage-x) 23 | * [Executing Babel-generated code](#toc-executing-babel-generated-code) 24 | * [`babel-polyfill`](#toc-babel-polyfill) 25 | * [`babel-runtime`](#toc-babel-runtime) 26 | * [Configuring Babel (Advanced)](#toc-configuring-babel-advanced) 27 | * [Manually specifying plugins](#toc-manually-specifying-plugins) 28 | * [Plugin options](#toc-plugin-options) 29 | * [Customizing Babel based on environment](#toc-customizing-babel-based-on-environment) 30 | * [Making your own preset](#toc-making-your-own-preset) 31 | * [Babel and other tools](#toc-babel-and-other-tools) 32 | * [Static analysis tools](#toc-static-analysis-tools) 33 | * [Linting](#toc-linting) 34 | * [Code Style](#toc-code-style) 35 | * [Documentation](#toc-documentation) 36 | * [Frameworks](#toc-frameworks) 37 | * [React](#toc-react) 38 | * [Text Editors and IDEs](#toc-text-editors-and-ides) 39 | * [Babel Support](#toc-babel-support) 40 | * [Babel Forum](#toc-babel-forum) 41 | * [Babel Chat](#toc-babel-chat) 42 | * [Babel Issues](#toc-babel-issues) 43 | * [Creating an awesome Babel bug report](#toc-creating-an-awesome-babel-bug-report) 44 | 45 | # Úvod 46 | 47 | Babel is a generic multi-purpose compiler for JavaScript. Using Babel you can use (and create) the next generation of JavaScript, as well as the next generation of JavaScript tooling. 48 | 49 | JavaScript as a language is constantly evolving, with new specs and proposals coming out with new features all the time. Using Babel will allow you to use many of these features years before they are available everywhere. 50 | 51 | Babel does this by compiling down JavaScript code written with the latest standards into a version that will work everywhere today. This process is known as source-to-source compiling, also known as transpiling. 52 | 53 | For example, Babel could transform the new ES2015 arrow function syntax from this: 54 | 55 | ```js 56 | const square = n => n * n; 57 | ``` 58 | 59 | Into the following: 60 | 61 | ```js 62 | const square = function square(n) { 63 | return n * n; 64 | }; 65 | ``` 66 | 67 | However, Babel can do much more than this as Babel has support for syntax extensions such as the JSX syntax for React and Flow syntax support for static type checking. 68 | 69 | Further than that, everything in Babel is simply a plugin and anyone can go out and create their own plugins using the full power of Babel to do whatever they want. 70 | 71 | *Even further* than that, Babel is broken down into a number of core modules that anyone can use to build the next generation of JavaScript tooling. 72 | 73 | Many people do too, the ecosystem that has sprung up around Babel is massive and very diverse. Throughout this handbook I'll be covering both how built-in Babel tools work as well as some useful things from around the community. 74 | 75 | > ***Aktualizace sledujte na Twitteru: [@thejameskyle](https://twitter.com/thejameskyle).*** 76 | 77 | * * * 78 | 79 | # Setting up Babel 80 | 81 | Since the JavaScript community has no single build tool, framework, platform, etc., Babel has official integrations for all of the major tooling. Everything from Gulp to Browserify, from Ember to Meteor, no matter what your setup looks like there is probably an official integration. 82 | 83 | For the purposes of this handbook, we're just going to cover the built-in ways of setting up Babel, but you can also visit the interactive [setup page](http://babeljs.io/docs/setup) for all of the integrations. 84 | 85 | > **Note:** This guide is going to refer to command line tools like `node` and `npm`. Before continuing any further you should be comfortable with these tools. 86 | 87 | ## `babel-cli` 88 | 89 | Babel's CLI is a simple way to compile files with Babel from the command line. 90 | 91 | Let's first install it globally to learn the basics. 92 | 93 | ```sh 94 | $ npm install --global babel-cli 95 | ``` 96 | 97 | We can compile our first file like so: 98 | 99 | ```sh 100 | $ babel my-file.js 101 | ``` 102 | 103 | This will dump the compiled output directly into your terminal. To write it to a file we'll specify an `--out-file` or `-o`. 104 | 105 | ```sh 106 | $ babel example.js --out-file compiled.js 107 | # or 108 | $ babel example.js -o compiled.js 109 | ``` 110 | 111 | If we want to compile a whole directory into a new directory we can do so using `--out-dir` or `-d`. 112 | 113 | ```sh 114 | $ babel src --out-dir lib 115 | # or 116 | $ babel src -d lib 117 | ``` 118 | 119 | ### Running Babel CLI from within a project 120 | 121 | While you *can* install Babel CLI globally on your machine, it's much better to install it **locally** project by project. 122 | 123 | There are two primary reasons for this. 124 | 125 | 1. Different projects on the same machine can depend on different versions of Babel allowing you to update one at a time. 126 | 2. It means you do not have an implicit dependency on the environment you are working in. Making your project far more portable and easier to setup. 127 | 128 | We can install Babel CLI locally by running: 129 | 130 | ```sh 131 | $ npm install --save-dev babel-cli 132 | ``` 133 | 134 | > **Note:** Since it's generally a bad idea to run Babel globally you may want to uninstall the global copy by running: 135 | > 136 | > ```sh 137 | $ npm uninstall --global babel-cli 138 | ``` 139 | 140 | After that finishes installing, your `package.json` file should look like this: 141 | 142 | ```json 143 | { 144 | "name": "my-project", 145 | "version": "1.0.0", 146 | "devDependencies": { 147 | "babel-cli": "^6.0.0" 148 | } 149 | } 150 | ``` 151 | 152 | Now instead of running Babel directly from the command line we're going to put our commands in **npm scripts** which will use our local version. 153 | 154 | Simply add a `"scripts"` field to your `package.json` and put the babel command inside there as `build`. 155 | 156 | ```diff 157 | { 158 | "name": "my-project", 159 | "version": "1.0.0", 160 | + "scripts": { 161 | + "build": "babel src -d lib" 162 | + }, 163 | "devDependencies": { 164 | "babel-cli": "^6.0.0" 165 | } 166 | } 167 | ``` 168 | 169 | Now from our terminal we can run: 170 | 171 | ```js 172 | npm run build 173 | ``` 174 | 175 | This will run Babel the same way as before, only now we are using a local copy. 176 | 177 | ## `babel-register` 178 | 179 | The next most common method of running Babel is through `babel-register`. This option will allow you to run Babel just by requiring files, which may integrate with your setup better. 180 | 181 | Note that this is not meant for production use. It's considered bad practice to deploy code that gets compiled this way. It is far better to compile ahead of time before deploying. However this works quite well for build scripts or other things that you run locally. 182 | 183 | First let's create an `index.js` file in our project. 184 | 185 | ```js 186 | console.log("Hello world!"); 187 | ``` 188 | 189 | If we were to run this with `node index.js` this wouldn't be compiled with Babel. So instead of doing that, we'll setup `babel-register`. 190 | 191 | First install `babel-register`. 192 | 193 | ```sh 194 | $ npm install --save-dev babel-register 195 | ``` 196 | 197 | Next, create a `register.js` file in the project and write the following code: 198 | 199 | ```js 200 | require("babel-register"); 201 | require("./index.js"); 202 | ``` 203 | 204 | What this does is *registers* Babel in Node's module system and begins compiling every file that is `require`'d. 205 | 206 | Now, instead of running `node index.js` we can use `register.js` instead. 207 | 208 | ```sh 209 | $ node register.js 210 | ``` 211 | 212 | > **Note:** You can't register Babel in the same file that you want to compile. As node is executing the file before Babel has a chance to compile it. 213 | > 214 | > ```js 215 | require("babel-register"); 216 | // not compiled: 217 | console.log("Hello world!"); 218 | ``` 219 | 220 | ## `babel-node` 221 | 222 | If you are just running some code via the `node` CLI the easiest way to integrate Babel might be to use the `babel-node` CLI which largely is just a drop in replacement for the `node` CLI. 223 | 224 | Note that this is not meant for production use. It's considered bad practice to deploy code that gets compiled this way. It is far better to compile ahead of time before deploying. However this works quite well for build scripts or other things that you run locally. 225 | 226 | First make sure that you have `babel-cli` installed. 227 | 228 | ```sh 229 | $ npm install --save-dev babel-cli 230 | ``` 231 | 232 | > **Note:** If you are wondering why we are installing this locally, please read the [Running Babel CLI from within a project](#toc-running-babel-cli-from-within-a-project) section above. 233 | 234 | Then replace wherever you are running `node` with `babel-node`. 235 | 236 | If you are using npm `scripts` you can simply do: 237 | 238 | ```diff 239 | { 240 | "scripts": { 241 | - "script-name": "node script.js" 242 | + "script-name": "babel-node script.js" 243 | } 244 | } 245 | ``` 246 | 247 | Otherwise you'll need to write out the path to `babel-node` itself. 248 | 249 | ```diff 250 | - node script.js 251 | + ./node_modules/.bin/babel-node script.js 252 | ``` 253 | 254 | > Tip: You can also use [`npm-run`](https://www.npmjs.com/package/npm-run). 255 | 256 | ## `babel-core` 257 | 258 | If you need to use Babel programmatically for some reason, you can use the `babel-core` package itself. 259 | 260 | First install `babel-core`. 261 | 262 | ```sh 263 | $ npm install babel-core 264 | ``` 265 | 266 | ```js 267 | var babel = require("babel-core"); 268 | ``` 269 | 270 | If you have a string of JavaScript you can compile it directly using `babel.transform`. 271 | 272 | ```js 273 | babel.transform("code();", options); 274 | // => { code, map, ast } 275 | ``` 276 | 277 | If you are working with files you can use either the asynchronous api: 278 | 279 | ```js 280 | babel.transformFile("filename.js", options, function(err, result) { 281 | result; // => { code, map, ast } 282 | }); 283 | ``` 284 | 285 | Or the synchronous api: 286 | 287 | ```js 288 | babel.transformFileSync("filename.js", options); 289 | // => { code, map, ast } 290 | ``` 291 | 292 | If you already have a Babel AST for whatever reason you may transform from the AST directly. 293 | 294 | ```js 295 | babel.transformFromAst(ast, code, options); 296 | // => { code, map, ast } 297 | ``` 298 | 299 | For all of the above methods, `options` refers to https://babeljs.io/docs/usage/api/#options. 300 | 301 | * * * 302 | 303 | # Configuring Babel 304 | 305 | You may have noticed by now that running Babel on its own doesn't seem to do anything other than copy JavaScript files from one location to another. 306 | 307 | This is because we haven't told Babel to do anything yet. 308 | 309 | > Since Babel is a general purpose compiler that gets used in a myriad of different ways, it doesn't do anything by default. You have to explicitly tell Babel what it should be doing. 310 | 311 | You can give Babel instructions on what to do by installing **plugins** or **presets** (groups of plugins). 312 | 313 | ## `.babelrc` 314 | 315 | Before we start telling Babel what to do. We need to create a configuration file. All you need to do is create a `.babelrc` file at the root of your project. Start off with it like this: 316 | 317 | ```js 318 | { 319 | "presets": [], 320 | "plugins": [] 321 | } 322 | ``` 323 | 324 | This file is how you configure Babel to do what you want. 325 | 326 | > **Note:** While you can also pass options to Babel in other ways the `.babelrc` file is convention and is the best way. 327 | 328 | ## `babel-preset-es2015` 329 | 330 | Let's start by telling Babel to compile ES2015 (the newest version of the JavaScript standard, also known as ES6) to ES5 (the version available in most JavaScript environments today). 331 | 332 | We'll do this by installing the "es2015" Babel preset: 333 | 334 | ```sh 335 | $ npm install --save-dev babel-preset-es2015 336 | ``` 337 | 338 | Next we'll modify our `.babelrc` to include that preset. 339 | 340 | ```diff 341 | { 342 | "presets": [ 343 | + "es2015" 344 | ], 345 | "plugins": [] 346 | } 347 | ``` 348 | 349 | ## `babel-preset-react` 350 | 351 | Setting up React is just as easy. Just install the preset: 352 | 353 | ```sh 354 | $ npm install --save-dev babel-preset-react 355 | ``` 356 | 357 | Then add the preset to your `.babelrc` file: 358 | 359 | ```diff 360 | { 361 | "presets": [ 362 | "es2015", 363 | + "react" 364 | ], 365 | "plugins": [] 366 | } 367 | ``` 368 | 369 | ## `babel-preset-stage-x` 370 | 371 | JavaScript also has some proposals that are making their way into the standard through the TC39's (the technical committee behind the ECMAScript standard) process. 372 | 373 | This process is broken through a 5 stage (0-4) process. As proposals gain more traction and are more likely to be accepted into the standard they proceed through the various stages, finally being accepted into the standard at stage 4. 374 | 375 | These are bundled in babel as 4 different presets: 376 | 377 | * `babel-preset-stage-0` 378 | * `babel-preset-stage-1` 379 | * `babel-preset-stage-2` 380 | * `babel-preset-stage-3` 381 | 382 | > Note that there is no stage-4 preset as it is simply the `es2015` preset above. 383 | 384 | Each of these presets requires the preset for the later stages. i.e. `babel-preset-stage-1` requires `babel-preset-stage-2` which requires `babel-preset-stage-3`. 385 | 386 | Simply install the stage you are interested in using: 387 | 388 | ```sh 389 | $ npm install --save-dev babel-preset-stage-2 390 | ``` 391 | 392 | Then you can add it to your `.babelrc` config. 393 | 394 | ```diff 395 | { 396 | "presets": [ 397 | "es2015", 398 | "react", 399 | + "stage-2" 400 | ], 401 | "plugins": [] 402 | } 403 | ``` 404 | 405 | * * * 406 | 407 | # Executing Babel-generated code 408 | 409 | So you've compiled your code with Babel, but this is not the end of the story. 410 | 411 | ## `babel-polyfill` 412 | 413 | Almost all futuristic JavaScript syntax can be compiled with Babel, but the same is not true for APIs. 414 | 415 | For example, the following code has an arrow function that needs to be compiled: 416 | 417 | ```js 418 | function addAll() { 419 | return Array.from(arguments).reduce((a, b) => a + b); 420 | } 421 | ``` 422 | 423 | Which turns into this: 424 | 425 | ```js 426 | function addAll() { 427 | return Array.from(arguments).reduce(function(a, b) { 428 | return a + b; 429 | }); 430 | } 431 | ``` 432 | 433 | However, this still won't work everywhere because `Array.from` doesn't exist in every JavaScript environment. 434 | 435 | Uncaught TypeError: Array.from is not a function 436 | 437 | 438 | To solve this problem we use something called a [Polyfill](https://remysharp.com/2010/10/08/what-is-a-polyfill). Simply put, a polyfill is a piece of code that replicates a native api that does not exist in the current runtime. Allowing you to use APIs such as `Array.from` before they are available. 439 | 440 | Babel uses the excellent [core-js](https://github.com/zloirock/core-js) as its polyfill, along with a customized [regenerator](https://github.com/facebook/regenerator) runtime for getting generators and async functions working. 441 | 442 | To include the Babel polyfill, first install it with npm: 443 | 444 | ```sh 445 | $ npm install --save babel-polyfill 446 | ``` 447 | 448 | Then simply include the polyfill at the top of any file that requires it: 449 | 450 | ```js 451 | import "babel-polyfill"; 452 | ``` 453 | 454 | ## `babel-runtime` 455 | 456 | In order to implement details of ECMAScript specs, Babel will use "helper" methods in order to keep the generated code clean. 457 | 458 | Since these helpers can get pretty long, and they get added to the top of every file you can move them into a single "runtime" which gets required. 459 | 460 | Start by installing `babel-plugin-transform-runtime` and `babel-runtime`: 461 | 462 | ```sh 463 | $ npm install --save-dev babel-plugin-transform-runtime 464 | $ npm install --save babel-runtime 465 | ``` 466 | 467 | Then update your `.babelrc`: 468 | 469 | ```diff 470 | { 471 | "plugins": [ 472 | + "transform-runtime", 473 | "transform-es2015-classes" 474 | ] 475 | } 476 | ``` 477 | 478 | Now Babel will compile code like the following: 479 | 480 | ```js 481 | class Foo { 482 | method() {} 483 | } 484 | ``` 485 | 486 | Into this: 487 | 488 | ```js 489 | import _classCallCheck from "babel-runtime/helpers/classCallCheck"; 490 | import _createClass from "babel-runtime/helpers/createClass"; 491 | 492 | let Foo = function () { 493 | function Foo() { 494 | _classCallCheck(this, Foo); 495 | } 496 | 497 | _createClass(Foo, [{ 498 | key: "method", 499 | value: function method() {} 500 | }]); 501 | 502 | return Foo; 503 | }(); 504 | ``` 505 | 506 | Rather than putting the `_classCallCheck` and `_createClass` helpers in every single file where they are needed. 507 | 508 | * * * 509 | 510 | # Configuring Babel (Advanced) 511 | 512 | Most people can get by using Babel with just the built-in presets, but Babel exposes much finer-grained power than that. 513 | 514 | ## Manually specifying plugins 515 | 516 | Babel presets are simply collections of pre-configured plugins, if you want to do something differently you manually specify plugins. This works almost exactly the same way as presets. 517 | 518 | First install a plugin: 519 | 520 | ```sh 521 | $ npm install --save-dev babel-plugin-transform-es2015-classes 522 | ``` 523 | 524 | Then add the `plugins` field to your `.babelrc`. 525 | 526 | ```diff 527 | { 528 | + "plugins": [ 529 | + "transform-es2015-classes" 530 | + ] 531 | } 532 | ``` 533 | 534 | This gives you much finer grained control over the exact transforms you are running. 535 | 536 | For a full list of official plugins see the [Babel Plugins page](http://babeljs.io/docs/plugins/). 537 | 538 | Also take a look at all the plugins that have been [built by the community](https://www.npmjs.com/search?q=babel-plugin). If you would like to learn how to write your own plugin read the [Babel Plugin Handbook](plugin-handbook.md). 539 | 540 | ## Plugin options 541 | 542 | Many plugins also have options to configure them to behave differently. For example, many transforms have a "loose" mode which drops some spec behavior in favor of simpler and more performant generated code. 543 | 544 | To add options to a plugin, simply make the following change: 545 | 546 | ```diff 547 | { 548 | "plugins": [ 549 | - "transform-es2015-classes" 550 | + ["transform-es2015-classes", { "loose": true }] 551 | ] 552 | } 553 | ``` 554 | 555 | > I'll be working on updates to the plugin documentation to detail every option in the coming weeks. [Follow me for updates](https://twitter.com/thejameskyle). 556 | 557 | ## Customizing Babel based on environment 558 | 559 | Babel plugins solve many different tasks. Many of them are development tools that can help you debugging your code or integrate with tools. There are also a lot of plugins that are meant for optimizing your code in production. 560 | 561 | For this reason, it is common to want Babel configuration based on the environment. You can do this easily with your `.babelrc` file. 562 | 563 | ```diff 564 | { 565 | "presets": ["es2015"], 566 | "plugins": [], 567 | + "env": { 568 | + "development": { 569 | + "plugins": [...] 570 | + }, 571 | + "production": { 572 | + "plugins": [...] 573 | + } 574 | } 575 | } 576 | ``` 577 | 578 | Babel will enable configuration inside of `env` based on the current environment. 579 | 580 | The current environment will use `process.env.BABEL_ENV`. When `BABEL_ENV` is not available, it will fallback to `NODE_ENV`, and if that is not available it will default to `"development"`. 581 | 582 | **Unix** 583 | 584 | ```sh 585 | $ BABEL_ENV=production [COMMAND] 586 | $ NODE_ENV=production [COMMAND] 587 | ``` 588 | 589 | **Windows** 590 | 591 | ```sh 592 | $ SET BABEL_ENV=production 593 | $ [COMMAND] 594 | ``` 595 | 596 | > **Note:** `[COMMAND]` is whatever you use to run Babel (ie. `babel`, `babel-node`, or maybe just `node` if you are using the register hook). 597 | > 598 | > **Tip:** If you want your command to work across unix and windows platforms then use [`cross-env`](https://www.npmjs.com/package/cross-env). 599 | 600 | ## Making your own preset 601 | 602 | Manually specifying plugins? Plugin options? Environment-based settings? All this configuration might seem like a ton of repetition for all of your projects. 603 | 604 | For this reason, we encourage the community to create their own presets. This could be a preset for the specific [node version](https://github.com/leebenson/babel-preset-node5) you are running, or maybe a preset for your [entire](https://github.com/cloudflare/babel-preset-cf) [company](https://github.com/airbnb/babel-preset-airbnb). 605 | 606 | It's easy to create a preset. Say you have this `.babelrc` file: 607 | 608 | ```js 609 | { 610 | "presets": [ 611 | "es2015", 612 | "react" 613 | ], 614 | "plugins": [ 615 | "transform-flow-strip-types" 616 | ] 617 | } 618 | ``` 619 | 620 | All you need to do is create a new project following the naming convention `babel-preset-*` (please be responsible with this namespace), and create two files. 621 | 622 | First, create a new `package.json` file with the necessary `dependencies` for your preset. 623 | 624 | ```js 625 | { 626 | "name": "babel-preset-my-awesome-preset", 627 | "version": "1.0.0", 628 | "author": "James Kyle ", 629 | "dependencies": { 630 | "babel-preset-es2015": "^6.3.13", 631 | "babel-preset-react": "^6.3.13", 632 | "babel-plugin-transform-flow-strip-types": "^6.3.15" 633 | } 634 | } 635 | ``` 636 | 637 | Then create an `index.js` file that exports the contents of your `.babelrc` file, replacing plugin/preset strings with `require` calls. 638 | 639 | ```js 640 | module.exports = { 641 | presets: [ 642 | require("babel-preset-es2015"), 643 | require("babel-preset-react") 644 | ], 645 | plugins: [ 646 | require("babel-plugin-transform-flow-strip-types") 647 | ] 648 | }; 649 | ``` 650 | 651 | Then simply publish this to npm and you can use it like you would any preset. 652 | 653 | * * * 654 | 655 | # Babel and other tools 656 | 657 | Babel is pretty straight forward to setup once you get the hang of it, but it can be rather difficult navigating how to set it up with other tools. However, we try to work closely with other projects in order to make the experience as easy as possible. 658 | 659 | ## Static analysis tools 660 | 661 | Newer standards bring a lot of new syntax to the language and static analysis tools are just starting to take advantage of it. 662 | 663 | ### Linting 664 | 665 | One of the most popular tools for linting is [ESLint](http://eslint.org), because of this we maintain an official [`babel-eslint`](https://github.com/babel/babel-eslint) integration. 666 | 667 | First install `eslint` and `babel-eslint`. 668 | 669 | ```sh 670 | $ npm install --save-dev eslint babel-eslint 671 | ``` 672 | 673 | Next create or use the existing `.eslintrc` file in your project and set the `parser` as `babel-eslint`. 674 | 675 | ```diff 676 | { 677 | + "parser": "babel-eslint", 678 | "rules": { 679 | ... 680 | } 681 | } 682 | ``` 683 | 684 | Now add a `lint` task to your npm `package.json` scripts: 685 | 686 | ```diff 687 | { 688 | "name": "my-module", 689 | "scripts": { 690 | + "lint": "eslint my-files.js" 691 | }, 692 | "devDependencies": { 693 | "babel-eslint": "...", 694 | "eslint": "..." 695 | } 696 | } 697 | ``` 698 | 699 | Then just run the task and you will be all setup. 700 | 701 | ```sh 702 | $ npm run lint 703 | ``` 704 | 705 | For more information consult the [`babel-eslint`](https://github.com/babel/babel-eslint) or [`eslint`](http://eslint.org) documentation. 706 | 707 | ### Code Style 708 | 709 | > JSCS has merged with ESLint, so checkout Code Styling with ESLint. 710 | 711 | JSCS is an extremely popular tool for taking linting a step further into checking the style of the code itself. A core maintainer of both the Babel and JSCS projects ([@hzoo](https://github.com/hzoo)) maintains an official integration with JSCS. 712 | 713 | Even better, this integration now lives within JSCS itself under the `--esnext` option. So integrating Babel is as easy as: 714 | 715 | $ jscs . --esnext 716 | 717 | 718 | From the cli, or adding the `esnext` option to your `.jscsrc` file. 719 | 720 | ```diff 721 | { 722 | "preset": "airbnb", 723 | + "esnext": true 724 | } 725 | ``` 726 | 727 | For more information consult the [`babel-jscs`](https://github.com/jscs-dev/babel-jscs) or [`jscs`](http://jscs.info) documentation. 728 | 729 | 734 | 735 | ### Documentation 736 | 737 | Using Babel, ES2015, and Flow you can infer a lot about your code. Using [documentation.js](http://documentation.js.org) you can generate detailed API documentation very easily. 738 | 739 | Documentation.js uses Babel behind the scenes to support all of the latest syntax including Flow annotations in order to declare the types in your code. 740 | 741 | ## Frameworks 742 | 743 | All of the major JavaScript frameworks are now focused on aligning their APIs around the future of the language. Because of this, there has been a lot of work going into the tooling. 744 | 745 | Frameworks have the opportunity not just to use Babel but to extend it in ways that improve their users' experience. 746 | 747 | ### React 748 | 749 | React has dramatically changed their API to align with ES2015 classes ([Read about the updated API here](https://babeljs.io/blog/2015/06/07/react-on-es6-plus)). Even further, React relies on Babel to compile it's JSX syntax, deprecating it's own custom tooling in favor of Babel. You can start by setting up the `babel-preset-react` package following the [instructions above](#babel-preset-react). 750 | 751 | The React community took Babel and ran with it. There are now a number of transforms [built by the community](https://www.npmjs.com/search?q=babel-plugin+react). 752 | 753 | Most notably the [`babel-plugin-react-transform`](https://github.com/gaearon/babel-plugin-react-transform) plugin which combined with a number of [React-specific transforms](https://github.com/gaearon/babel-plugin-react-transform#transforms) can enable things like *hot module reloading* and other debugging utilities. 754 | 755 | 760 | 761 | ## Text Editors and IDEs 762 | 763 | Introducing ES2015, JSX, and Flow syntax with Babel can be helpful, but if your text editor doesn't support it then it can be a really bad experience. For this reason you will want to setup your text editor or IDE with a Babel plugin. 764 | 765 | * [Sublime Text](https://github.com/babel/babel-sublime) 766 | * [Atom](https://atom.io/packages/language-babel) 767 | * [Vim](https://github.com/jbgutierrez/vim-babel) 768 | * [WebStorm](https://babeljs.io/docs/setup/#webstorm) 769 | 770 | 775 | 776 | * * * 777 | 778 | # Babel Support 779 | 780 | Babel has a very large and quickly growing community, as we grow we want to ensure that people have all the resources they need to be successful. So we provide a number of different channels for getting support. 781 | 782 | Remember that across all of these communities we enforce a [Code of Conduct](https://github.com/babel/babel/blob/master/CODE_OF_CONDUCT.md). If you break the Code of Conduct, action will be taken. So please read it and be conscious of it when interacting with others. 783 | 784 | We are also looking to grow a self-supporting community, for people who stick around and support others. If you find someone asking a question you know the answer to, take a few minutes and help them out. Try your best to be kind and understanding when doing so. 785 | 786 | ## Babel Forum 787 | 788 | [Discourse](http://www.discourse.org) has provided us with a hosted version of their forum software for free (and we love them for it!). If forums are your thing please stop by [discuss.babeljs.io](https://discuss.babeljs.io). 789 | 790 | ## Babel Chat 791 | 792 | Everyone loves [Slack](https://slack.com). If you're looking for immediate support from the community then come chat with us at [slack.babeljs.io](https://slack.babeljs.io). 793 | 794 | 799 | 800 | ## Babel Issues 801 | 802 | Babel uses the issue tracker provided by [Github](http://github.com). 803 | 804 | You can see all the open and closed issues on [Github](https://github.com/babel/babel/issues). 805 | 806 | If you want to open a new issue: 807 | 808 | * [Search for an existing issue](https://github.com/babel/babel/issues) 809 | * [Create a new bug report](https://github.com/babel/babel/issues/new) or [request a new feature](https://github.com/babel/babel/issues/new) 810 | 811 | ### Creating an awesome Babel bug report 812 | 813 | Babel issues can sometimes be very difficult to debug remotely, so we need all the help we can get. Spending a few more minutes crafting a really nice bug report can help get your problem solved significantly faster. 814 | 815 | First, try isolating your problem. It's extremely unlikely that every part of your setup is contributing to the problem. If your problem is a piece of input code, try deleting as much code as possible that still causes an issue. 816 | 817 | > [WIP] 818 | 819 | * * * 820 | 821 | > ***Aktualizace sledujte na Twitteru: [@thejameskyle](https://twitter.com/thejameskyle).*** --------------------------------------------------------------------------------