Full Code of jamiebuilds/babel-handbook for AI

master c6828415127f cached
105 files
2.7 MB
722.2k tokens
1 requests
Download .txt
Showing preview only (2,887K chars total). Download the full file or copy to clipboard to get everything.
Repository: jamiebuilds/babel-handbook
Branch: master
Commit: c6828415127f
Files: 105
Total size: 2.7 MB

Directory structure:
gitextract__u4zmoof/

├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── crowdin.yaml
├── package.json
└── translations/
    ├── af/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── ar/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── ca/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── cs/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── da/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── de/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── el/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── en/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── es-ES/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── fa-IR/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── fi/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── fr/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── he/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── hu/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── id-ID/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── it/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── ja/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── ko/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── nl/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── no/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── pl/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── pt-BR/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── pt-PT/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── ro/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── ru/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── sk-SK/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── sr/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── sv-SE/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── tr/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── uk/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── vi/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── zh-Hans/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    └── zh-Hant/
        ├── README.md
        ├── plugin-handbook.md
        └── user-handbook.md

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
node_modules
*.log


================================================
FILE: CONTRIBUTING.md
================================================
# Contributing

### Translating the handbook

The English translation of this handbook is maintained in this repository, for
other translations we use [Crowdin](https://crowdin.com/), if you would like to
contribute to one of the translations you can invite yourself to the Crowdin
Project [here](https://crowdin.com/project/babel-plugin-handbook/invite).

Changes to the English translation will automatically be sent to Crowdin which
will notify translators of changes. When translations are completed, they will be
built and sent back to GitHub. There's a short delay, but if any part of this
process does not happen, please open an issue.

Once you set up your account on Crowdin you should be taken to
[this page](https://crowdin.com/project/babel-plugin-handbook).

Click on the language you would like to contribute to and then click on
"README.md". You will be taken to the translation editor.

![Crowdin Translation Editor](https://cloud.githubusercontent.com/assets/952783/12076790/291e6cac-b170-11e5-989e-4cb2925e2b38.png)

On the left side you can see the handbook. In red are missing translations,
light green are translated, and dark green are translated and verified.

If you click on one of the sections, it will bring it up in the center panel
where you can enter a translation and save it.

If you click on a section with text formatting or links, Crowdin has a special
syntax for matching up the formatting.

![Crowdin translation format](https://cloud.githubusercontent.com/assets/952783/12076803/c1a83a52-b170-11e5-9925-329b129be959.png)

If you match the numbered `<0>...</0>` delimiters, Crowdin will build the final
translation with all the formatting and links of the original.

Once a translation is finished, it should only be a few minutes before the
changes get pushed to GitHub automatically.


================================================
FILE: LICENSE
================================================
Creative Commons Attribution 4.0 International

=======================================================================

Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.

Using Creative Commons Public Licenses

Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.

     Considerations for licensors: Our public licenses are
     intended for use by those authorized to give the public
     permission to use material in ways otherwise restricted by
     copyright and certain other rights. Our licenses are
     irrevocable. Licensors should read and understand the terms
     and conditions of the license they choose before applying it.
     Licensors should also secure all rights necessary before
     applying our licenses so that the public can reuse the
     material as expected. Licensors should clearly mark any
     material not subject to the license. This includes other CC-
     licensed material, or material used under an exception or
     limitation to copyright. More considerations for licensors:
  wiki.creativecommons.org/Considerations_for_licensors

     Considerations for the public: By using one of our public
     licenses, a licensor grants the public permission to use the
     licensed material under specified terms and conditions. If
     the licensor's permission is not necessary for any reason--for
     example, because of any applicable exception or limitation to
     copyright--then that use is not regulated by the license. Our
     licenses grant only permissions under copyright and certain
     other rights that a licensor has authority to grant. Use of
     the licensed material may still be restricted for other
     reasons, including because others have copyright or other
     rights in the material. A licensor may make special requests,
     such as asking that all changes be marked or described.
     Although not required by our licenses, you are encouraged to
     respect those requests where reasonable. More_considerations
     for the public:
  wiki.creativecommons.org/Considerations_for_licensees

=======================================================================

Creative Commons Attribution 4.0 International Public License

By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution 4.0 International Public License ("Public License"). To the
extent this Public License may be interpreted as a contract, You are
granted the Licensed Rights in consideration of Your acceptance of
these terms and conditions, and the Licensor grants You such rights in
consideration of benefits the Licensor receives from making the
Licensed Material available under these terms and conditions.


Section 1 -- Definitions.

  a. Adapted Material means material subject to Copyright and Similar
     Rights that is derived from or based upon the Licensed Material
     and in which the Licensed Material is translated, altered,
     arranged, transformed, or otherwise modified in a manner requiring
     permission under the Copyright and Similar Rights held by the
     Licensor. For purposes of this Public License, where the Licensed
     Material is a musical work, performance, or sound recording,
     Adapted Material is always produced where the Licensed Material is
     synched in timed relation with a moving image.

  b. Adapter's License means the license You apply to Your Copyright
     and Similar Rights in Your contributions to Adapted Material in
     accordance with the terms and conditions of this Public License.

  c. Copyright and Similar Rights means copyright and/or similar rights
     closely related to copyright including, without limitation,
     performance, broadcast, sound recording, and Sui Generis Database
     Rights, without regard to how the rights are labeled or
     categorized. For purposes of this Public License, the rights
     specified in Section 2(b)(1)-(2) are not Copyright and Similar
     Rights.

  d. Effective Technological Measures means those measures that, in the
     absence of proper authority, may not be circumvented under laws
     fulfilling obligations under Article 11 of the WIPO Copyright
     Treaty adopted on December 20, 1996, and/or similar international
     agreements.

  e. Exceptions and Limitations means fair use, fair dealing, and/or
     any other exception or limitation to Copyright and Similar Rights
     that applies to Your use of the Licensed Material.

  f. Licensed Material means the artistic or literary work, database,
     or other material to which the Licensor applied this Public
     License.

  g. Licensed Rights means the rights granted to You subject to the
     terms and conditions of this Public License, which are limited to
     all Copyright and Similar Rights that apply to Your use of the
     Licensed Material and that the Licensor has authority to license.

  h. Licensor means the individual(s) or entity(ies) granting rights
     under this Public License.

  i. Share means to provide material to the public by any means or
     process that requires permission under the Licensed Rights, such
     as reproduction, public display, public performance, distribution,
     dissemination, communication, or importation, and to make material
     available to the public including in ways that members of the
     public may access the material from a place and at a time
     individually chosen by them.

  j. Sui Generis Database Rights means rights other than copyright
     resulting from Directive 96/9/EC of the European Parliament and of
     the Council of 11 March 1996 on the legal protection of databases,
     as amended and/or succeeded, as well as other essentially
     equivalent rights anywhere in the world.

  k. You means the individual or entity exercising the Licensed Rights
     under this Public License. Your has a corresponding meaning.


Section 2 -- Scope.

  a. License grant.

       1. Subject to the terms and conditions of this Public License,
          the Licensor hereby grants You a worldwide, royalty-free,
          non-sublicensable, non-exclusive, irrevocable license to
          exercise the Licensed Rights in the Licensed Material to:

            a. reproduce and Share the Licensed Material, in whole or
               in part; and

            b. produce, reproduce, and Share Adapted Material.

       2. Exceptions and Limitations. For the avoidance of doubt, where
          Exceptions and Limitations apply to Your use, this Public
          License does not apply, and You do not need to comply with
          its terms and conditions.

       3. Term. The term of this Public License is specified in Section
          6(a).

       4. Media and formats; technical modifications allowed. The
          Licensor authorizes You to exercise the Licensed Rights in
          all media and formats whether now known or hereafter created,
          and to make technical modifications necessary to do so. The
          Licensor waives and/or agrees not to assert any right or
          authority to forbid You from making technical modifications
          necessary to exercise the Licensed Rights, including
          technical modifications necessary to circumvent Effective
          Technological Measures. For purposes of this Public License,
          simply making modifications authorized by this Section 2(a)
          (4) never produces Adapted Material.

       5. Downstream recipients.

            a. Offer from the Licensor -- Licensed Material. Every
               recipient of the Licensed Material automatically
               receives an offer from the Licensor to exercise the
               Licensed Rights under the terms and conditions of this
               Public License.

            b. No downstream restrictions. You may not offer or impose
               any additional or different terms or conditions on, or
               apply any Effective Technological Measures to, the
               Licensed Material if doing so restricts exercise of the
               Licensed Rights by any recipient of the Licensed
               Material.

       6. No endorsement. Nothing in this Public License constitutes or
          may be construed as permission to assert or imply that You
          are, or that Your use of the Licensed Material is, connected
          with, or sponsored, endorsed, or granted official status by,
          the Licensor or others designated to receive attribution as
          provided in Section 3(a)(1)(A)(i).

  b. Other rights.

       1. Moral rights, such as the right of integrity, are not
          licensed under this Public License, nor are publicity,
          privacy, and/or other similar personality rights; however, to
          the extent possible, the Licensor waives and/or agrees not to
          assert any such rights held by the Licensor to the limited
          extent necessary to allow You to exercise the Licensed
          Rights, but not otherwise.

       2. Patent and trademark rights are not licensed under this
          Public License.

       3. To the extent possible, the Licensor waives any right to
          collect royalties from You for the exercise of the Licensed
          Rights, whether directly or through a collecting society
          under any voluntary or waivable statutory or compulsory
          licensing scheme. In all other cases the Licensor expressly
          reserves any right to collect such royalties.


Section 3 -- License Conditions.

Your exercise of the Licensed Rights is expressly made subject to the
following conditions.

  a. Attribution.

       1. If You Share the Licensed Material (including in modified
          form), You must:

            a. retain the following if it is supplied by the Licensor
               with the Licensed Material:

                 i. identification of the creator(s) of the Licensed
                    Material and any others designated to receive
                    attribution, in any reasonable manner requested by
                    the Licensor (including by pseudonym if
                    designated);

                ii. a copyright notice;

               iii. a notice that refers to this Public License;

                iv. a notice that refers to the disclaimer of
                    warranties;

                 v. a URI or hyperlink to the Licensed Material to the
                    extent reasonably practicable;

            b. indicate if You modified the Licensed Material and
               retain an indication of any previous modifications; and

            c. indicate the Licensed Material is licensed under this
               Public License, and include the text of, or the URI or
               hyperlink to, this Public License.

       2. You may satisfy the conditions in Section 3(a)(1) in any
          reasonable manner based on the medium, means, and context in
          which You Share the Licensed Material. For example, it may be
          reasonable to satisfy the conditions by providing a URI or
          hyperlink to a resource that includes the required
          information.

       3. If requested by the Licensor, You must remove any of the
          information required by Section 3(a)(1)(A) to the extent
          reasonably practicable.

       4. If You Share Adapted Material You produce, the Adapter's
          License You apply must not prevent recipients of the Adapted
          Material from complying with this Public License.


Section 4 -- Sui Generis Database Rights.

Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:

  a. for the avoidance of doubt, Section 2(a)(1) grants You the right
     to extract, reuse, reproduce, and Share all or a substantial
     portion of the contents of the database;

  b. if You include all or a substantial portion of the database
     contents in a database in which You have Sui Generis Database
     Rights, then the database in which You have Sui Generis Database
     Rights (but not its individual contents) is Adapted Material; and

  c. You must comply with the conditions in Section 3(a) if You Share
     all or a substantial portion of the contents of the database.

For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.


Section 5 -- Disclaimer of Warranties and Limitation of Liability.

  a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
     EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
     AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
     ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
     IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
     WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
     PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
     ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
     KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
     ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.

  b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
     TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
     NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
     INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
     COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
     USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
     ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
     DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
     IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.

  c. The disclaimer of warranties and limitation of liability provided
     above shall be interpreted in a manner that, to the extent
     possible, most closely approximates an absolute disclaimer and
     waiver of all liability.


Section 6 -- Term and Termination.

  a. This Public License applies for the term of the Copyright and
     Similar Rights licensed here. However, if You fail to comply with
     this Public License, then Your rights under this Public License
     terminate automatically.

  b. Where Your right to use the Licensed Material has terminated under
     Section 6(a), it reinstates:

       1. automatically as of the date the violation is cured, provided
          it is cured within 30 days of Your discovery of the
          violation; or

       2. upon express reinstatement by the Licensor.

     For the avoidance of doubt, this Section 6(b) does not affect any
     right the Licensor may have to seek remedies for Your violations
     of this Public License.

  c. For the avoidance of doubt, the Licensor may also offer the
     Licensed Material under separate terms or conditions or stop
     distributing the Licensed Material at any time; however, doing so
     will not terminate this Public License.

  d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
     License.


Section 7 -- Other Terms and Conditions.

  a. The Licensor shall not be bound by any additional or different
     terms or conditions communicated by You unless expressly agreed.

  b. Any arrangements, understandings, or agreements regarding the
     Licensed Material not stated herein are separate from and
     independent of the terms and conditions of this Public License.


Section 8 -- Interpretation.

  a. For the avoidance of doubt, this Public License does not, and
     shall not be interpreted to, reduce, limit, restrict, or impose
     conditions on any use of the Licensed Material that could lawfully
     be made without permission under this Public License.

  b. To the extent possible, if any provision of this Public License is
     deemed unenforceable, it shall be automatically reformed to the
     minimum extent necessary to make it enforceable. If the provision
     cannot be reformed, it shall be severed from this Public License
     without affecting the enforceability of the remaining terms and
     conditions.

  c. No term or condition of this Public License will be waived and no
     failure to comply consented to unless expressly agreed to by the
     Licensor.

  d. Nothing in this Public License constitutes or may be interpreted
     as a limitation upon, or waiver of, any privileges and immunities
     that apply to the Licensor or You, including from the legal
     processes of any jurisdiction or authority.


=======================================================================

Creative Commons is not a party to its public licenses.
Notwithstanding, Creative Commons may elect to apply one of its public
licenses to material it publishes and in those instances will be
considered the "Licensor." Except for the limited purpose of indicating
that material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the public
licenses.

Creative Commons may be contacted at creativecommons.org.


================================================
FILE: README.md
================================================
# Babel Handbook

Written by [Jamie Kyle](https://jamie.build/)

A guided handbook on how to use Babel and how to create plugins for Babel.

**Translations**

- [English](https://github.com/thejameskyle/babel-handbook/tree/master/translations/en/README.md)
- [Afrikaans](https://github.com/thejameskyle/babel-handbook/tree/master/translations/af/README.md)
- [العربية](https://github.com/thejameskyle/babel-handbook/tree/master/translations/ar/README.md)
- [Català](https://github.com/thejameskyle/babel-handbook/tree/master/translations/ca/README.md)
- [Čeština](https://github.com/thejameskyle/babel-handbook/tree/master/translations/cs/README.md)
- [Dansk](https://github.com/thejameskyle/babel-handbook/tree/master/translations/da/README.md)
- [Deutsch](https://github.com/thejameskyle/babel-handbook/tree/master/translations/de/README.md)
- [Ελληνικά](https://github.com/thejameskyle/babel-handbook/tree/master/translations/el/README.md)
- [Español](https://github.com/thejameskyle/babel-handbook/tree/master/translations/es-ES/README.md)
- [فارسی](https://github.com/thejameskyle/babel-handbook/tree/master/translations/fa-IR/README.md)
- [Français](https://github.com/thejameskyle/babel-handbook/tree/master/translations/fr/README.md)
- [עִברִית](https://github.com/thejameskyle/babel-handbotree/master/ok/translations/he/README.md)
- [Italiano](https://github.com/thejameskyle/babel-handbook/tree/master/translations/it/README.md)
- [日本語](https://github.com/thejameskyle/babel-handbook/tree/master/translations/ja/README.md)
- [한국어](https://github.com/thejameskyle/babel-handbook/tree/master/translations/ko/README.md)
- [Magyar](https://github.com/thejameskyle/babel-handbook/tree/master/translations/hu/README.md)
- [Nederlands](https://github.com/thejameskyle/babel-handbook/tree/master/translations/nl/README.md)
- [Norsk](https://github.com/thejameskyle/babel-handbook/tree/master/translations/no/README.md)
- [Polskie](https://github.com/thejameskyle/babel-handbook/tree/master/translations/pl/README.md)
- [Português](https://github.com/thejameskyle/babel-handbook/tree/master/translations/pt-PT/README.md)
- [Português (Brasil)](https://github.com/thejameskyle/babel-handbook/tree/master/translations/pt-BR/README.md)
- [Română](https://github.com/thejameskyle/babel-handbook/tree/master/translations/ro/README.md)
- [Русский](https://github.com/thejameskyle/babel-handbook/tree/master/translations/ru/README.md)
- [Српски језик (Ћирилица)](https://github.com/thejameskyle/babel-handbook/tree/master/translations/sr/README.md)
- [Suomi](https://github.com/thejameskyle/babel-handbook/tree/master/translations/fi/README.md)
- [Svenska](https://github.com/thejameskyle/babel-handbook/tree/master/translations/sv-SE/README.md)
- [Türkçe](https://github.com/thejameskyle/babel-handbook/tree/master/translations/tr/README.md)
- [Tiếng Việt](https://github.com/thejameskyle/babel-handbook/tree/master/translations/vi/README.md)
- [Українська](https://github.com/thejameskyle/babel-handbook/tree/master/translations/uk/README.md)
- [中文](https://github.com/thejameskyle/babel-handbook/tree/master/translations/zh-Hans/README.md)
- [繁體中文](https://github.com/thejameskyle/babel-handbook/tree/master/translations/zh-Hant/README.md)

**[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])**

If you are reading a non-English translation of this document 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).

Special thanks to [@sebmck](https://github.com/sebmck/),
[@hzoo](https://github.com/hzoo),
[@jdalton](https://github.com/jdalton),
[@abraithwaite](https://github.com/abraithwaite),
[@robey](https://github.com/robey), and others for their
amazing help on this handbook.


================================================
FILE: crowdin.yaml
================================================
project_identifier: babel-plugin-handbook
api_key_env: CROWDIN_API_KEY
base_path: .
files:
  - source: '/translations/en/**/*.md'
    translation: '/translations/%locale%/**/%original_file_name%'
    languages_mapping:
      locale:
        'af': 'af'
        'ar': 'ar'
        'ca': 'ca'
        'cs': 'cs'
        'da': 'da'
        'de': 'de'
        'el': 'el'
        'es-ES': 'es-ES'
        'fi': 'fi'
        'fr': 'fr'
        'he': 'he'
        'hu': 'hu'
        'it': 'it'
        'ja': 'ja'
        'ko': 'ko'
        'no': 'no'
        'nl': 'nl'
        'pl': 'pl'
        'pt-BR': 'pt-BR'
        'pt-PT': 'pt-PT'
        'ro': 'ro'
        'ru': 'ru'
        'sr': 'sr'
        'sv-SE': 'sv-SE'
        'tr': 'tr'
        'uk': 'uk'
        'vi': 'vi'
        'zh-CN': 'zh-Hans'
        'zh-TW': 'zh-Hant'


================================================
FILE: package.json
================================================
{
  "name": "babel-handbook",
  "version": "1.0.0",
  "description": "How to Babel",
  "repository": "thejameskyle/babel-handbook.git",
  "homepage": "https://github.com/thejameskyle/babel-handbook",
  "keywords": [
    "documentation",
    "guide",
    "handbook",
    "babel",
    "plugin"
  ],
  "author": "James Kyle <me@thejameskyle.com>",
  "license": "cc-by-4.0"
}


================================================
FILE: translations/af/README.md
================================================
# Babel Handbook

This handbook is divided into two parts:

  * [User Handbook](user-handbook.md) - How to setup/configure Babel and more.
  * [Plugin Handbook](plugin-handbook.md) - How to create plugins for Babel.

> For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) on Twitter.

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

================================================
FILE: translations/af/plugin-handbook.md
================================================
# Babel Plugin Handbook

This document covers how to create [Babel](https://babeljs.io) [plugins](https://babeljs.io/docs/advanced/plugins/).

[![cc-by-4.0](https://licensebuttons.net/l/by/4.0/80x15.png)](http://creativecommons.org/licenses/by/4.0/)

This handbook is available in other languages, see the [README](/README.md) for a complete list.

# Table of Contents

  * [Introduction](#toc-introduction)
  * [Basics](#toc-basics) 
      * [ASTs](#toc-asts)
      * [Stages of Babel](#toc-stages-of-babel)
      * [Parse](#toc-parse) 
          * [Lexical Analysis](#toc-lexical-analysis)
          * [Syntactic Analysis](#toc-syntactic-analysis)
      * [Transform](#toc-transform)
      * [Generate](#toc-generate)
      * [Traversal](#toc-traversal)
      * [Visitors](#toc-visitors)
      * [Paths](#toc-paths) 
          * [Paths in Visitors](#toc-paths-in-visitors)
      * [State](#toc-state)
      * [Scopes](#toc-scopes) 
          * [Bindings](#toc-bindings)
  * [API](#toc-api) 
      * [babylon](#toc-babylon)
      * [babel-traverse](#toc-babel-traverse)
      * [babel-types](#toc-babel-types)
      * [Definitions](#toc-definitions)
      * [Builders](#toc-builders)
      * [Validators](#toc-validators)
      * [Converters](#toc-converters)
      * [babel-generator](#toc-babel-generator)
      * [babel-template](#toc-babel-template)
  * [Writing your first Babel Plugin](#toc-writing-your-first-babel-plugin)
  * [Transformation Operations](#toc-transformation-operations) 
      * [Visiting](#toc-visiting)
      * [Get the Path of Sub-Node](#toc-get-the-path-of-a-sub-node)
      * [Check if a node is a certain type](#toc-check-if-a-node-is-a-certain-type)
      * [Check if a path is a certain type](#toc-check-if-a-path-is-a-certain-type)
      * [Check if an identifier is referenced](#toc-check-if-an-identifier-is-referenced)
      * [Find a specific parent path](#toc-find-a-specific-parent-path)
      * [Get Sibling Paths](#toc-get-sibling-paths)
      * [Stopping Traversal](#toc-stopping-traversal)
      * [Manipulation](#toc-manipulation)
      * [Replacing a node](#toc-replacing-a-node)
      * [Replacing a node with multiple nodes](#toc-replacing-a-node-with-multiple-nodes)
      * [Replacing a node with a source string](#toc-replacing-a-node-with-a-source-string)
      * [Inserting a sibling node](#toc-inserting-a-sibling-node)
      * [Inserting into a container](#toc-inserting-into-a-container)
      * [Removing a node](#toc-removing-a-node)
      * [Replacing a parent](#toc-replacing-a-parent)
      * [Removing a parent](#toc-removing-a-parent)
      * [Scope](#toc-scope)
      * [Checking if a local variable is bound](#toc-checking-if-a-local-variable-is-bound)
      * [Generating a UID](#toc-generating-a-uid)
      * [Pushing a variable declaration to a parent scope](#toc-pushing-a-variable-declaration-to-a-parent-scope)
      * [Rename a binding and its references](#toc-rename-a-binding-and-its-references)
  * [Plugin Options](#toc-plugin-options) 
      * [Pre and Post in Plugins](#toc-pre-and-post-in-plugins)
      * [Enabling Syntax in Plugins](#toc-enabling-syntax-in-plugins)
  * [Building Nodes](#toc-building-nodes)
  * [Best Practices](#toc-best-practices) 
      * [Avoid traversing the AST as much as possible](#toc-avoid-traversing-the-ast-as-much-as-possible)
      * [Merge visitors whenever possible](#toc-merge-visitors-whenever-possible)
      * [Do not traverse when manual lookup will do](#toc-do-not-traverse-when-manual-lookup-will-do)
      * [Optimizing nested visitors](#toc-optimizing-nested-visitors)
      * [Being aware of nested structures](#toc-being-aware-of-nested-structures)
      * [Unit Testing](#toc-unit-testing)

# <a id="toc-introduction"></a>Introduction

Babel is a generic multi-purpose compiler for JavaScript. More than that it is a collection of modules that can be used for many different forms of static analysis.

> Static analysis is the process of analyzing code without executing it. (Analysis of code while executing it is known as dynamic analysis). The purpose of static analysis varies greatly. It can be used for linting, compiling, code highlighting, code transformation, optimization, minification, and much more.

You can use Babel to build many different types of tools that can help you be more productive and write better programs.

> ***For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) on Twitter.***

* * *

# <a id="toc-basics"></a>Basics

Babel is a JavaScript compiler, specifically a source-to-source compiler, often called a "transpiler". This means that you give Babel some JavaScript code, Babel modifies the code, and generates the new code back out.

## <a id="toc-asts"></a>ASTs

Each of these steps involve creating or working with an [Abstract Syntax Tree](https://en.wikipedia.org/wiki/Abstract_syntax_tree) or AST.

> Babel uses an AST modified from [ESTree](https://github.com/estree/estree), with the core spec located [here](https://github.com/babel/babylon/blob/master/ast/spec.md).

```js
function square(n) {
  return n * n;
}
```

> Check out [AST Explorer](http://astexplorer.net/) to get a better sense of the AST nodes. [Here](http://astexplorer.net/#/Z1exs6BWMq) is a link to it with the example code above pasted in.

This same program can be represented as a tree like this:

```md
- FunctionDeclaration:
  - id:
    - Identifier:
      - name: square
  - params [1]
    - Identifier
      - name: n
  - body:
    - BlockStatement
      - body [1]
        - ReturnStatement
          - argument
            - BinaryExpression
              - operator: *
              - left
                - Identifier
                  - name: n
              - right
                - Identifier
                  - name: n
```

Or as a JavaScript Object like this:

```js
{
  type: "FunctionDeclaration",
  id: {
    type: "Identifier",
    name: "square"
  },
  params: [{
    type: "Identifier",
    name: "n"
  }],
  body: {
    type: "BlockStatement",
    body: [{
      type: "ReturnStatement",
      argument: {
        type: "BinaryExpression",
        operator: "*",
        left: {
          type: "Identifier",
          name: "n"
        },
        right: {
          type: "Identifier",
          name: "n"
        }
      }
    }]
  }
}
```

You'll notice that each level of the AST has a similar structure:

```js
{
  type: "FunctionDeclaration",
  id: {...},
  params: [...],
  body: {...}
}
```

```js
{
  type: "Identifier",
  name: ...
}
```

```js
{
  type: "BinaryExpression",
  operator: ...,
  left: {...},
  right: {...}
}
```

> Note: Some properties have been removed for simplicity.

Each of these are known as a **Node**. An AST can be made up of a single Node, or hundreds if not thousands of Nodes. Together they are able to describe the syntax of a program that can be used for static analysis.

Every Node has this interface:

```typescript
interface Node {
  type: string;
}
```

The `type` field is a string representing the type of Node the object is (ie. `"FunctionDeclaration"`, `"Identifier"`, or `"BinaryExpression"`). Each type of Node defines an additional set of properties that describe that particular node type.

There are additional properties on every Node that Babel generates which describe the position of the Node in the original source code.

```js
{
  type: ...,
  start: 0,
  end: 38,
  loc: {
    start: {
      line: 1,
      column: 0
    },
    end: {
      line: 3,
      column: 1
    }
  },
  ...
}
```

These properties `start`, `end`, `loc`, appear in every single Node.

## <a id="toc-stages-of-babel"></a>Stages of Babel

The three primary stages of Babel are **parse**, **transform**, **generate**.

### <a id="toc-parse"></a>Parse

The **parse** stage, takes code and outputs an AST. There are two phases of parsing in Babel: [**Lexical Analysis**](https://en.wikipedia.org/wiki/Lexical_analysis) and [**Syntactic Analysis**](https://en.wikipedia.org/wiki/Parsing).

#### <a id="toc-lexical-analysis"></a>Lexical Analysis

Lexical Analysis will take a string of code and turn it into a stream of **tokens**.

You can think of tokens as a flat array of language syntax pieces.

```js
n * n;
```

```js
[
  { type: { ... }, value: "n", start: 0, end: 1, loc: { ... } },
  { type: { ... }, value: "*", start: 2, end: 3, loc: { ... } },
  { type: { ... }, value: "n", start: 4, end: 5, loc: { ... } },
  ...
]
```

Each of the `type`s here have a set of properties describing the token:

```js
{
  type: {
    label: 'name',
    keyword: undefined,
    beforeExpr: false,
    startsExpr: true,
    rightAssociative: false,
    isLoop: false,
    isAssign: false,
    prefix: false,
    postfix: false,
    binop: null,
    updateContext: null
  },
  ...
}
```

Like AST nodes they also have a `start`, `end`, and `loc`.

#### <a id="toc-syntactic-analysis"></a>Syntactic Analysis

Syntactic Analysis will take a stream of tokens and turn it into an AST representation. Using the information in the tokens, this phase will reformat them as an AST which represents the structure of the code in a way that makes it easier to work with.

### <a id="toc-transform"></a>Transform

The [transform](https://en.wikipedia.org/wiki/Program_transformation) stage takes an AST and traverses through it, adding, updating, and removing nodes as it goes along. This is by far the most complex part of Babel or any compiler. This is where plugins operate and so it will be the subject of most of this handbook. So we won't dive too deep right now.

### <a id="toc-generate"></a>Generate

The [code generation](https://en.wikipedia.org/wiki/Code_generation_(compiler)) stage takes the final AST and turns it back into a string of code, also creating [source maps](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/).

Code generation is pretty simple: you traverse through the AST depth-first, building a string that represents the transformed code.

## <a id="toc-traversal"></a>Traversal

When you want to transform an AST you have to [traverse the tree](https://en.wikipedia.org/wiki/Tree_traversal) recursively.

Say we have the type `FunctionDeclaration`. It has a few properties: `id`, `params`, and `body`. Each of them have nested nodes.

```js
{
  type: "FunctionDeclaration",
  id: {
    type: "Identifier",
    name: "square"
  },
  params: [{
    type: "Identifier",
    name: "n"
  }],
  body: {
    type: "BlockStatement",
    body: [{
      type: "ReturnStatement",
      argument: {
        type: "BinaryExpression",
        operator: "*",
        left: {
          type: "Identifier",
          name: "n"
        },
        right: {
          type: "Identifier",
          name: "n"
        }
      }
    }]
  }
}
```

So we start at the `FunctionDeclaration` and we know its internal properties so we visit each of them and their children in order.

Next we go to `id` which is an `Identifier`. `Identifier`s don't have any child node properties so we move on.

After that is `params` which is an array of nodes so we visit each of them. In this case it's a single node which is also an `Identifier` so we move on.

Then we hit `body` which is a `BlockStatement` with a property `body` that is an array of Nodes so we go to each of them.

The only item here is a `ReturnStatement` node which has an `argument`, we go to the `argument` and find a `BinaryExpression`.

The `BinaryExpression` has an `operator`, a `left`, and a `right`. The operator isn't a node, just a value, so we don't go to it, and instead just visit `left` and `right`.

This traversal process happens throughout the Babel transform stage.

### <a id="toc-visitors"></a>Visitors

When we talk about "going" to a node, we actually mean we are **visiting** them. The reason we use that term is because there is this concept of a [**visitor**](https://en.wikipedia.org/wiki/Visitor_pattern).

Visitors are a pattern used in AST traversal across languages. Simply put they are an object with methods defined for accepting particular node types in a tree. That's a bit abstract so let's look at an example.

```js
const MyVisitor = {
  Identifier() {
    console.log("Called!");
  }
};

// You can also create a visitor and add methods on it later
let visitor = {};
visitor.MemberExpression = function() {};
visitor.FunctionDeclaration = function() {}
```

> **Note:** `Identifier() { ... }` is shorthand for `Identifier: { enter() { ... } }`.

This is a basic visitor that when used during a traversal will call the `Identifier()` method for every `Identifier` in the tree.

So with this code the `Identifier()` method will be called four times with each `Identifier` (including `square`).

```js
function square(n) {
  return n * n;
}
```

```js
path.traverse(MyVisitor);
Called!
Called!
Called!
Called!
```

These calls are all on node **enter**. However there is also the possibility of calling a visitor method when on **exit**.

Imagine we have this tree structure:

```js
- FunctionDeclaration
  - Identifier (id)
  - Identifier (params[0])
  - BlockStatement (body)
    - ReturnStatement (body)
      - BinaryExpression (argument)
        - Identifier (left)
        - Identifier (right)
```

As we traverse down each branch of the tree we eventually hit dead ends where we need to traverse back up the tree to get to the next node. Going down the tree we **enter** each node, then going back up we **exit** each node.

Let's *walk* through what this process looks like for the above tree.

  * Enter `FunctionDeclaration` 
      * Enter `Identifier (id)`
      * Hit dead end
      * Exit `Identifier (id)`
      * Enter `Identifier (params[0])`
      * Hit dead end
      * Exit `Identifier (params[0])`
      * Enter `BlockStatement (body)`
      * Enter `ReturnStatement (body)` 
          * Enter `BinaryExpression (argument)`
          * Enter `Identifier (left)` 
              * Hit dead end
          * Exit `Identifier (left)`
          * Enter `Identifier (right)` 
              * Hit dead end
          * Exit `Identifier (right)`
          * Exit `BinaryExpression (argument)`
      * Exit `ReturnStatement (body)`
      * Exit `BlockStatement (body)`
  * Exit `FunctionDeclaration`

So when creating a visitor you have two opportunities to visit a node.

```js
const MyVisitor = {
  Identifier: {
    enter() {
      console.log("Entered!");
    },
    exit() {
      console.log("Exited!");
    }
  }
};
```

If necessary, you can also apply the same function for multiple visitor nodes by separating them with a `|` in the method name as a string like `Identifier|MemberExpression`.

Example usage in the [flow-comments](https://github.com/babel/babel/blob/2b6ff53459d97218b0cf16f8a51c14a165db1fd2/packages/babel-plugin-transform-flow-comments/src/index.js#L47) plugin

```js
const MyVisitor = {
  "ExportNamedDeclaration|Flow"(path) {}
};
```

You can also use aliases as visitor nodes (as defined in [babel-types](https://github.com/babel/babel/tree/master/packages/babel-types/src/definitions)).

For example,

`Function` is an alias for `FunctionDeclaration`, `FunctionExpression`, `ArrowFunctionExpression`, `ObjectMethod` and `ClassMethod`.

```js
const MyVisitor = {
  Function(path) {}
};
```

### <a id="toc-paths"></a>Paths

An AST generally has many Nodes, but how do Nodes relate to one another? We could have one giant mutable object that you manipulate and have full access to, or we can simplify this with **Paths**.

A **Path** is an object representation of the link between two nodes.

For example if we take the following node and its child:

```js
{
  type: "FunctionDeclaration",
  id: {
    type: "Identifier",
    name: "square"
  },
  ...
}
```

And represent the child `Identifier` as a path, it looks something like this:

```js
{
  "parent": {
    "type": "FunctionDeclaration",
    "id": {...},
    ....
  },
  "node": {
    "type": "Identifier",
    "name": "square"
  }
}
```

It also has additional metadata about the path:

```js
{
  "parent": {...},
  "node": {...},
  "hub": {...},
  "contexts": [],
  "data": {},
  "shouldSkip": false,
  "shouldStop": false,
  "removed": false,
  "state": null,
  "opts": null,
  "skipKeys": null,
  "parentPath": null,
  "context": null,
  "container": null,
  "listKey": null,
  "inList": false,
  "parentKey": null,
  "key": null,
  "scope": null,
  "type": null,
  "typeAnnotation": null
}
```

As well as tons and tons of methods related to adding, updating, moving, and removing nodes, but we'll get into those later.

In a sense, paths are a **reactive** representation of a node's position in the tree and all sorts of information about the node. Whenever you call a method that modifies the tree, this information is updated. Babel manages all of this for you to make working with nodes easy and as stateless as possible.

#### <a id="toc-paths-in-visitors"></a>Paths in Visitors

When you have a visitor that has a `Identifier()` method, you're actually visiting the path instead of the node. This way you are mostly working with the reactive representation of a node instead of the node itself.

```js
const MyVisitor = {
  Identifier(path) {
    console.log("Visiting: " + path.node.name);
  }
};
```

```js
a + b + c;
```

```js
path.traverse(MyVisitor);
Visiting: a
Visiting: b
Visiting: c
```

### <a id="toc-state"></a>State

State is the enemy of AST transformation. State will bite you over and over again and your assumptions about state will almost always be proven wrong by some syntax that you didn't consider.

Take the following code:

```js
function square(n) {
  return n * n;
}
```

Let's write a quick hacky visitor that will rename `n` to `x`.

```js
let paramName;

const MyVisitor = {
  FunctionDeclaration(path) {
    const param = path.node.params[0];
    paramName = param.name;
    param.name = "x";
  },

  Identifier(path) {
    if (path.node.name === paramName) {
      path.node.name = "x";
    }
  }
};
```

This might work for the above code, but we can easily break that by doing this:

```js
function square(n) {
  return n * n;
}
n;
```

The better way to deal with this is recursion. So let's make like a Christopher Nolan film and put a visitor inside of a visitor.

```js
const updateParamNameVisitor = {
  Identifier(path) {
    if (path.node.name === this.paramName) {
      path.node.name = "x";
    }
  }
};

const MyVisitor = {
  FunctionDeclaration(path) {
    const param = path.node.params[0];
    const paramName = param.name;
    param.name = "x";

    path.traverse(updateParamNameVisitor, { paramName });
  }
};

path.traverse(MyVisitor);
```

Of course, this is a contrived example but it demonstrates how to eliminate global state from your visitors.

### <a id="toc-scopes"></a>Scopes

Next let's introduce the concept of a [**scope**](https://en.wikipedia.org/wiki/Scope_(computer_science)). JavaScript has [lexical scoping](https://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping_vs._dynamic_scoping), which is a tree structure where blocks create new scope.

```js
// global scope

function scopeOne() {
  // scope 1

  function scopeTwo() {
    // scope 2
  }
}
```

Whenever you create a reference in JavaScript, whether that be by a variable, function, class, param, import, label, etc., it belongs to the current scope.

```js
var global = "I am in the global scope";

function scopeOne() {
  var one = "I am in the scope created by `scopeOne()`";

  function scopeTwo() {
    var two = "I am in the scope created by `scopeTwo()`";
  }
}
```

Code within a deeper scope may use a reference from a higher scope.

```js
function scopeOne() {
  var one = "I am in the scope created by `scopeOne()`";

  function scopeTwo() {
    one = "I am updating the reference in `scopeOne` inside `scopeTwo`";
  }
}
```

A lower scope might also create a reference of the same name without modifying it.

```js
function scopeOne() {
  var one = "I am in the scope created by `scopeOne()`";

  function scopeTwo() {
    var one = "I am creating a new `one` but leaving reference in `scopeOne()` alone.";
  }
}
```

When writing a transform, we want to be wary of scope. We need to make sure we don't break existing code while modifying different parts of it.

We may want to add new references and make sure they don't collide with existing ones. Or maybe we just want to find where a variable is referenced. We want to be able to track these references within a given scope.

A scope can be represented as:

```js
{
  path: path,
  block: path.node,
  parentBlock: path.parent,
  parent: parentScope,
  bindings: [...]
}
```

When you create a new scope you do so by giving it a path and a parent scope. Then during the traversal process it collects all the references ("bindings") within that scope.

Once that's done, there's all sorts of methods you can use on scopes. We'll get into those later though.

#### <a id="toc-bindings"></a>Bindings

References all belong to a particular scope; this relationship is known as a **binding**.

```js
function scopeOnce() {
  var ref = "This is a binding";

  ref; // This is a reference to a binding

  function scopeTwo() {
    ref; // This is a reference to a binding from a lower scope
  }
}
```

A single binding looks like this:

```js
{
  identifier: node,
  scope: scope,
  path: path,
  kind: 'var',

  referenced: true,
  references: 3,
  referencePaths: [path, path, path],

  constant: false,
  constantViolations: [path]
}
```

With this information you can find all the references to a binding, see what type of binding it is (parameter, declaration, etc.), lookup what scope it belongs to, or get a copy of its identifier. You can even tell if it's constant and if not, see what paths are causing it to be non-constant.

Being able to tell if a binding is constant is useful for many purposes, the largest of which is minification.

```js
function scopeOne() {
  var ref1 = "This is a constant binding";

  becauseNothingEverChangesTheValueOf(ref1);

  function scopeTwo() {
    var ref2 = "This is *not* a constant binding";
    ref2 = "Because this changes the value";
  }
}
```

* * *

# <a id="toc-api"></a>API

Babel is actually a collection of modules. In this section we'll walk through the major ones, explaining what they do and how to use them.

> Note: This is not a replacement for detailed API documentation which will be available elsewhere shortly.

## <a id="toc-babylon"></a>[`babylon`](https://github.com/babel/babylon)

Babylon is Babel's parser. Started as a fork of Acorn, it's fast, simple to use, has plugin-based architecture for non-standard features (as well as future standards).

First, let's install it.

```sh
$ npm install --save babylon
```

Let's start by simply parsing a string of code:

```js
import * as babylon from "babylon";

const code = `function square(n) {
  return n * n;
}`;

babylon.parse(code);
// Node {
//   type: "File",
//   start: 0,
//   end: 38,
//   loc: SourceLocation {...},
//   program: Node {...},
//   comments: [],
//   tokens: [...]
// }
```

We can also pass options to `parse()` like so:

```js
babylon.parse(code, {
  sourceType: "module", // default: "script"
  plugins: ["jsx"] // default: []
});
```

`sourceType` can either be `"module"` or `"script"` which is the mode that Babylon should parse in. `"module"` will parse in strict mode and allow module declarations, `"script"` will not.

> **Note:** `sourceType` defaults to `"script"` and will error when it finds `import` or `export`. Pass `sourceType: "module"` to get rid of these errors.

Since Babylon is built with a plugin-based architecture, there is also a `plugins` option which will enable the internal plugins. Note that Babylon has not yet opened this API to external plugins, although may do so in the future.

To see a full list of plugins, see the [Babylon README](https://github.com/babel/babylon/blob/master/README.md#plugins).

## <a id="toc-babel-traverse"></a>[`babel-traverse`](https://github.com/babel/babel/tree/master/packages/babel-traverse)

The Babel Traverse module maintains the overall tree state, and is responsible for replacing, removing, and adding nodes.

Install it by running:

```sh
$ npm install --save babel-traverse
```

We can use it alongside Babylon to traverse and update nodes:

```js
import * as babylon from "babylon";
import traverse from "babel-traverse";

const code = `function square(n) {
  return n * n;
}`;

const ast = babylon.parse(code);

traverse(ast, {
  enter(path) {
    if (
      path.node.type === "Identifier" &&
      path.node.name === "n"
    ) {
      path.node.name = "x";
    }
  }
});
```

## <a id="toc-babel-types"></a>[`babel-types`](https://github.com/babel/babel/tree/master/packages/babel-types)

Babel Types is a Lodash-esque utility library for AST nodes. It contains methods for building, validating, and converting AST nodes. It's useful for cleaning up AST logic with well thought out utility methods.

You can install it by running:

```sh
$ npm install --save babel-types
```

Then start using it:

```js
import traverse from "babel-traverse";
import * as t from "babel-types";

traverse(ast, {
  enter(path) {
    if (t.isIdentifier(path.node, { name: "n" })) {
      path.node.name = "x";
    }
  }
});
```

### <a id="toc-definitions"></a>Definitions

Babel Types has definitions for every single type of node, with information on what properties belong where, what values are valid, how to build that node, how the node should be traversed, and aliases of the Node.

A single node type definition looks like this:

```js
defineType("BinaryExpression", {
  builder: ["operator", "left", "right"],
  fields: {
    operator: {
      validate: assertValueType("string")
    },
    left: {
      validate: assertNodeType("Expression")
    },
    right: {
      validate: assertNodeType("Expression")
    }
  },
  visitor: ["left", "right"],
  aliases: ["Binary", "Expression"]
});
```

### <a id="toc-builders"></a>Builders

You'll notice the above definition for `BinaryExpression` has a field for a `builder`.

```js
builder: ["operator", "left", "right"]
```

This is because each node type gets a builder method, which when used looks like this:

```js
t.binaryExpression("*", t.identifier("a"), t.identifier("b"));
```

Which creates an AST like this:

```js
{
  type: "BinaryExpression",
  operator: "*",
  left: {
    type: "Identifier",
    name: "a"
  },
  right: {
    type: "Identifier",
    name: "b"
  }
}
```

Which when printed looks like this:

```js
a * b
```

Builders will also validate the nodes they are creating and throw descriptive errors if used improperly. Which leads into the next type of method.

### <a id="toc-validators"></a>Validators

The definition for `BinaryExpression` also includes information on the `fields` of a node and how to validate them.

```js
fields: {
  operator: {
    validate: assertValueType("string")
  },
  left: {
    validate: assertNodeType("Expression")
  },
  right: {
    validate: assertNodeType("Expression")
  }
}
```

This is used to create two types of validating methods. The first of which is `isX`.

```js
t.isBinaryExpression(maybeBinaryExpressionNode);
```

This tests to make sure that the node is a binary expression, but you can also pass a second parameter to ensure that the node contains certain properties and values.

```js
t.isBinaryExpression(maybeBinaryExpressionNode, { operator: "*" });
```

There is also the more, *ehem*, assertive version of these methods, which will throw errors instead of returning `true` or `false`.

```js
t.assertBinaryExpression(maybeBinaryExpressionNode);
t.assertBinaryExpression(maybeBinaryExpressionNode, { operator: "*" });
// Error: Expected type "BinaryExpression" with option { "operator": "*" }
```

### <a id="toc-converters"></a>Converters

> [WIP]

## <a id="toc-babel-generator"></a>[`babel-generator`](https://github.com/babel/babel/tree/master/packages/babel-generator)

Babel Generator is the code generator for Babel. It takes an AST and turns it into code with sourcemaps.

Run the following to install it:

```sh
$ npm install --save babel-generator
```

Then use it

```js
import * as babylon from "babylon";
import generate from "babel-generator";

const code = `function square(n) {
  return n * n;
}`;

const ast = babylon.parse(code);

generate(ast, {}, code);
// {
//   code: "...",
//   map: "..."
// }
```

You can also pass options to `generate()`.

```js
generate(ast, {
  retainLines: false,
  compact: "auto",
  concise: false,
  quotes: "double",
  // ...
}, code);
```

## <a id="toc-babel-template"></a>[`babel-template`](https://github.com/babel/babel/tree/master/packages/babel-template)

Babel Template is another tiny but incredibly useful module. It allows you to write strings of code with placeholders that you can use instead of manually building up a massive AST. In computer science, this capability is called quasiquotes.

```sh
$ npm install --save babel-template
```

```js
import template from "babel-template";
import generate from "babel-generator";
import * as t from "babel-types";

const buildRequire = template(`
  var IMPORT_NAME = require(SOURCE);
`);

const ast = buildRequire({
  IMPORT_NAME: t.identifier("myModule"),
  SOURCE: t.stringLiteral("my-module")
});

console.log(generate(ast).code);
```

```js
var myModule = require("my-module");
```

# <a id="toc-writing-your-first-babel-plugin"></a>Writing your first Babel Plugin

Now that you're familiar with all the basics of Babel, let's tie it together with the plugin API.

Start off with a `function` that gets passed the current [`babel`](https://github.com/babel/babel/tree/master/packages/babel-core) object.

```js
export default function(babel) {
  // plugin contents
}
```

Since you'll be using it so often, you'll likely want to grab just `babel.types` like so:

```js
export default function({ types: t }) {
  // plugin contents
}
```

Then you return an object with a property `visitor` which is the primary visitor for the plugin.

```js
export default function({ types: t }) {
  return {
    visitor: {
      // visitor contents
    }
  };
};
```

Each function in the visitor receives 2 arguments: `path` and `state`

```js
export default function({ types: t }) {
  return {
    visitor: {
      Identifier(path, state) {},
      ASTNodeTypeHere(path, state) {}
    }
  };
};
```

Let's write a quick plugin to show off how it works. Here's our source code:

```js
foo === bar;
```

Or in AST form:

```js
{
  type: "BinaryExpression",
  operator: "===",
  left: {
    type: "Identifier",
    name: "foo"
  },
  right: {
    type: "Identifier",
    name: "bar"
  }
}
```

We'll start off by adding a `BinaryExpression` visitor method.

```js
export default function({ types: t }) {
  return {
    visitor: {
      BinaryExpression(path) {
        // ...
      }
    }
  };
}
```

Then let's narrow it down to just `BinaryExpression`s that are using the `===` operator.

```js
visitor: {
  BinaryExpression(path) {
    if (path.node.operator !== "===") {
      return;
    }

    // ...
  }
}
```

Now let's replace the `left` property with a new identifier:

```js
BinaryExpression(path) {
  if (path.node.operator !== "===") {
    return;
  }

  path.node.left = t.identifier("sebmck");
  // ...
}
```

Already if we run this plugin we would get:

```js
sebmck === bar;
```

Now let's just replace the `right` property.

```js
BinaryExpression(path) {
  if (path.node.operator !== "===") {
    return;
  }

  path.node.left = t.identifier("sebmck");
  path.node.right = t.identifier("dork");
}
```

And now for our final result:

```js
sebmck === dork;
```

Awesome! Our very first Babel plugin.

* * *

# <a id="toc-transformation-operations"></a>Transformation Operations

## <a id="toc-visiting"></a>Visiting

### <a id="toc-get-the-path-of-a-sub-node"></a>Get the Path of Sub-Node

To access an AST node's property you normally access the node and then the property. `path.node.property`

```js
// the BinaryExpression AST node has properties: `left`, `right`, `operator`
BinaryExpression(path) {
  path.node.left;
  path.node.right;
  path.node.operator;
}
```

If you need to access the `path` of that property instead, use the `get` method of a path, passing in the string to the property.

```js
BinaryExpression(path) {
  path.get('left');
}
Program(path) {
  path.get('body.0');
}
```

### <a id="toc-check-if-a-node-is-a-certain-type"></a>Check if a node is a certain type

If you want to check what the type of a node is, the preferred way to do so is:

```js
BinaryExpression(path) {
  if (t.isIdentifier(path.node.left)) {
    // ...
  }
}
```

You can also do a shallow check for properties on that node:

```js
BinaryExpression(path) {
  if (t.isIdentifier(path.node.left, { name: "n" })) {
    // ...
  }
}
```

This is functionally equivalent to:

```js
BinaryExpression(path) {
  if (
    path.node.left != null &&
    path.node.left.type === "Identifier" &&
    path.node.left.name === "n"
  ) {
    // ...
  }
}
```

### <a id="toc-check-if-a-path-is-a-certain-type"></a>Check if a path is a certain type

A path has the same methods for checking the type of a node:

```js
BinaryExpression(path) {
  if (path.get('left').isIdentifier({ name: "n" })) {
    // ...
  }
}
```

is equivalent to doing:

```js
BinaryExpression(path) {
  if (t.isIdentifier(path.node.left, { name: "n" })) {
    // ...
  }
}
```

### <a id="toc-check-if-an-identifier-is-referenced"></a>Check if an identifier is referenced

```js
Identifier(path) {
  if (path.isReferencedIdentifier()) {
    // ...
  }
}
```

Alternatively:

```js
Identifier(path) {
  if (t.isReferenced(path.node, path.parent)) {
    // ...
  }
}
```

### <a id="toc-find-a-specific-parent-path"></a>Find a specific parent path

Sometimes you will need to traverse the tree upwards from a path until a condition is satisfied.

Call the provided `callback` with the `NodePath`s of all the parents. When the `callback` returns a truthy value, we return that `NodePath`.

```js
path.findParent((path) => path.isObjectExpression());
```

If the current path should be included as well:

```js
path.find((path) => path.isObjectExpression());
```

Find the closest parent function or program:

```js
path.getFunctionParent();
```

Walk up the tree until we hit a parent node path in a list

```js
path.getStatementParent();
```

### <a id="toc-get-sibling-paths"></a>Get Sibling Paths

If a path is in a list like in the body of a `Function`/`Program`, it will have "siblings".

  * Check if a path is part of a list with `path.inList`
  * You can get the surrounding siblings with `path.getSibling(index)`,
  * The current path's index in the container with `path.key`,
  * The path's container (an array of all sibling nodes) with `path.container`
  * Get the name of the key of the list container with `path.listKey`

> These APIs are used in the [transform-merge-sibling-variables](https://github.com/babel/babili/blob/master/packages/babel-plugin-transform-merge-sibling-variables/src/index.js) plugin used in [babel-minify](https://github.com/babel/babili).

```js
var a = 1; // pathA, path.key = 0
var b = 2; // pathB, path.key = 1
var c = 3; // pathC, path.key = 2
```

```js
export default function({ types: t }) {
  return {
    visitor: {
      VariableDeclaration(path) {
        // if the current path is pathA
        path.inList // true
        path.listKey // "body"
        path.key // 0
        path.getSibling(0) // pathA
        path.getSibling(path.key + 1) // pathB
        path.container // [pathA, pathB, pathC]
      }
    }
  };
}
```

### <a id="toc-stopping-traversal"></a>Stopping Traversal

If your plugin needs to not run in a certain situation, the simpliest thing to do is to write an early return.

```js
BinaryExpression(path) {
  if (path.node.operator !== '**') return;
}
```

If you are doing a sub-traversal in a top level path, you can use 2 provided API methods:

`path.skip()` skips traversing the children of the current path. `path.stop()` stops traversal entirely.

```js
outerPath.traverse({
  Function(innerPath) {
    innerPath.skip(); // if checking the children is irrelevant
  },
  ReferencedIdentifier(innerPath, state) {
    state.iife = true;
    innerPath.stop(); // if you want to save some state and then stop traversal, or deopt
  }
});
```

## <a id="toc-manipulation"></a>Manipulation

### <a id="toc-replacing-a-node"></a>Replacing a node

```js
BinaryExpression(path) {
  path.replaceWith(
    t.binaryExpression("**", path.node.left, t.numberLiteral(2))
  );
}
```

```diff
  function square(n) {
-   return n * n;
+   return n ** 2;
  }
```

### <a id="toc-replacing-a-node-with-multiple-nodes"></a>Replacing a node with multiple nodes

```js
ReturnStatement(path) {
  path.replaceWithMultiple([
    t.expressionStatement(t.stringLiteral("Is this the real life?")),
    t.expressionStatement(t.stringLiteral("Is this just fantasy?")),
    t.expressionStatement(t.stringLiteral("(Enjoy singing the rest of the song in your head)")),
  ]);
}
```

```diff
  function square(n) {
-   return n * n;
+   "Is this the real life?";
+   "Is this just fantasy?";
+   "(Enjoy singing the rest of the song in your head)";
  }
```

> **Note:** When replacing an expression with multiple nodes, they must be statements. This is because Babel uses heuristics extensively when replacing nodes which means that you can do some pretty crazy transformations that would be extremely verbose otherwise.

### <a id="toc-replacing-a-node-with-a-source-string"></a>Replacing a node with a source string

```js
FunctionDeclaration(path) {
  path.replaceWithSourceString(`function add(a, b) {
    return a + b;
  }`);
}
```

```diff
- function square(n) {
-   return n * n;
+ function add(a, b) {
+   return a + b;
  }
```

> **Note:** It's not recommended to use this API unless you're dealing with dynamic source strings, otherwise it's more efficient to parse the code outside of the visitor.

### <a id="toc-inserting-a-sibling-node"></a>Inserting a sibling node

```js
FunctionDeclaration(path) {
  path.insertBefore(t.expressionStatement(t.stringLiteral("Because I'm easy come, easy go.")));
  path.insertAfter(t.expressionStatement(t.stringLiteral("A little high, little low.")));
}
```

```diff
+ "Because I'm easy come, easy go.";
  function square(n) {
    return n * n;
  }
+ "A little high, little low.";
```

> **Note:** This should always be a statement or an array of statements. This uses the same heuristics mentioned in [Replacing a node with multiple nodes](#replacing-a-node-with-multiple-nodes).

### <a id="toc-inserting-into-a-container"></a>Inserting into a container

If you want to insert into a AST node property like that is an array like `body`. It is similar to `insertBefore`/`insertAfter` other than you having to specify the `listKey` which is usually `body`.

```js
ClassMethod(path) {
  path.get('body').unshiftContainer('body', t.expressionStatement(t.stringLiteral('before')));
  path.get('body').pushContainer('body', t.expressionStatement(t.stringLiteral('after')));
}
```

```diff
 class A {
  constructor() {
+   "before"
    var a = 'middle';
+   "after"
  }
 }
```

### <a id="toc-removing-a-node"></a>Removing a node

```js
FunctionDeclaration(path) {
  path.remove();
}
```

```diff
- function square(n) {
-   return n * n;
- }
```

### <a id="toc-replacing-a-parent"></a>Replacing a parent

Just call `replaceWith` with the parentPath: `path.parentPath`

```js
BinaryExpression(path) {
  path.parentPath.replaceWith(
    t.expressionStatement(t.stringLiteral("Anyway the wind blows, doesn't really matter to me, to me."))
  );
}
```

```diff
  function square(n) {
-   return n * n;
+   "Anyway the wind blows, doesn't really matter to me, to me.";
  }
```

### <a id="toc-removing-a-parent"></a>Removing a parent

```js
BinaryExpression(path) {
  path.parentPath.remove();
}
```

```diff
  function square(n) {
-   return n * n;
  }
```

## <a id="toc-scope"></a>Scope

### <a id="toc-checking-if-a-local-variable-is-bound"></a>Checking if a local variable is bound

```js
FunctionDeclaration(path) {
  if (path.scope.hasBinding("n")) {
    // ...
  }
}
```

This will walk up the scope tree and check for that particular binding.

You can also check if a scope has its **own** binding:

```js
FunctionDeclaration(path) {
  if (path.scope.hasOwnBinding("n")) {
    // ...
  }
}
```

### <a id="toc-generating-a-uid"></a>Generating a UID

This will generate an identifier that doesn't collide with any locally defined variables.

```js
FunctionDeclaration(path) {
  path.scope.generateUidIdentifier("uid");
  // Node { type: "Identifier", name: "_uid" }
  path.scope.generateUidIdentifier("uid");
  // Node { type: "Identifier", name: "_uid2" }
}
```

### <a id="toc-pushing-a-variable-declaration-to-a-parent-scope"></a>Pushing a variable declaration to a parent scope

Sometimes you may want to push a `VariableDeclaration` so you can assign to it.

```js
FunctionDeclaration(path) {
  const id = path.scope.generateUidIdentifierBasedOnNode(path.node.id);
  path.remove();
  path.scope.parent.push({ id, init: path.node });
}
```

```diff
- function square(n) {
+ var _square = function square(n) {
    return n * n;
- }
+ };
```

### <a id="toc-rename-a-binding-and-its-references"></a>Rename a binding and its references

```js
FunctionDeclaration(path) {
  path.scope.rename("n", "x");
}
```

```diff
- function square(n) {
-   return n * n;
+ function square(x) {
+   return x * x;
  }
```

Alternatively, you can rename a binding to a generated unique identifier:

```js
FunctionDeclaration(path) {
  path.scope.rename("n");
}
```

```diff
- function square(n) {
-   return n * n;
+ function square(_n) {
+   return _n * _n;
  }
```

* * *

# <a id="toc-plugin-options"></a>Plugin Options

If you would like to let your users customize the behavior of your Babel plugin you can accept plugin specific options which users can specify like this:

```js
{
  plugins: [
    ["my-plugin", {
      "option1": true,
      "option2": false
    }]
  ]
}
```

These options then get passed into plugin visitors through the `state` object:

```js
export default function({ types: t }) {
  return {
    visitor: {
      FunctionDeclaration(path, state) {
        console.log(state.opts);
        // { option1: true, option2: false }
      }
    }
  }
}
```

These options are plugin-specific and you cannot access options from other plugins.

## <a id="toc-pre-and-post-in-plugins"></a> Pre and Post in Plugins

Plugins can have functions that are run before or after plugins. They can be used for setup or cleanup/analysis purposes.

```js
export default function({ types: t }) {
  return {
    pre(state) {
      this.cache = new Map();
    },
    visitor: {
      StringLiteral(path) {
        this.cache.set(path.node.value, 1);
      }
    },
    post(state) {
      console.log(this.cache);
    }
  };
}
```

## <a id="toc-enabling-syntax-in-plugins"></a> Enabling Syntax in Plugins

Plugins can enable [babylon plugins](https://github.com/babel/babylon#plugins) so that users don't need to install/enable them. This prevents a parsing error without inheriting the syntax plugin.

```js
export default function({ types: t }) {
  return {
    inherits: require("babel-plugin-syntax-jsx")
  };
}
```

## <a id="toc-throwing-a-syntax-error"></a> Throwing a Syntax Error

If you want to throw an error with babel-code-frame and a message:

```js
export default function({ types: t }) {
  return {
    visitor: {
      StringLiteral(path) {
        throw path.buildCodeFrameError("Error message here");
      }
    }
  };
}
```

The error looks like:

    file.js: Error message here
       7 |
       8 | let tips = [
    >  9 |   "Click on any AST node with a '+' to expand it",
         |   ^
      10 |
      11 |   "Hovering over a node highlights the \
      12 |    corresponding part in the source code",
    

* * *

# <a id="toc-building-nodes"></a>Building Nodes

When writing transformations you'll often want to build up some nodes to insert into the AST. As mentioned previously, you can do this using the [builder](#builders) methods in the [`babel-types`](#babel-types) package.

The method name for a builder is simply the name of the node type you want to build except with the first letter lowercased. For example if you wanted to build a `MemberExpression` you would use `t.memberExpression(...)`.

The arguments of these builders are decided by the node definition. There's some work that's being done to generate easy-to-read documentation on the definitions, but for now they can all be found [here](https://github.com/babel/babel/tree/master/packages/babel-types/src/definitions).

A node definition looks like the following:

```js
defineType("MemberExpression", {
  builder: ["object", "property", "computed"],
  visitor: ["object", "property"],
  aliases: ["Expression", "LVal"],
  fields: {
    object: {
      validate: assertNodeType("Expression")
    },
    property: {
      validate(node, key, val) {
        let expectedType = node.computed ? "Expression" : "Identifier";
        assertNodeType(expectedType)(node, key, val);
      }
    },
    computed: {
      default: false
    }
  }
});
```

Here you can see all the information about this particular node type, including how to build it, traverse it, and validate it.

By looking at the `builder` property, you can see the 3 arguments that will be needed to call the builder method (`t.memberExpression`).

```js
builder: ["object", "property", "computed"],
```

> Note that sometimes there are more properties that you can customize on the node than the `builder` array contains. This is to keep the builder from having too many arguments. In these cases you need to set the properties manually. An example of this is [`ClassMethod`](https://github.com/babel/babel/blob/bbd14f88c4eea88fa584dd877759dd6b900bf35e/packages/babel-types/src/definitions/es2015.js#L238-L276).

```js
// Example
// because the builder doesn't contain `async` as a property
var node = t.classMethod(
  "constructor",
  t.identifier("constructor"),
  params,
  body
)
// set it manually after creation
node.async = true;
```

You can see the validation for the builder arguments with the `fields` object.

```js
fields: {
  object: {
    validate: assertNodeType("Expression")
  },
  property: {
    validate(node, key, val) {
      let expectedType = node.computed ? "Expression" : "Identifier";
      assertNodeType(expectedType)(node, key, val);
    }
  },
  computed: {
    default: false
  }
}
```

You can see that `object` needs to be an `Expression`, `property` either needs to be an `Expression` or an `Identifier` depending on if the member expression is `computed` or not and `computed` is simply a boolean that defaults to `false`.

So we can construct a `MemberExpression` by doing the following:

```js
t.memberExpression(
  t.identifier('object'),
  t.identifier('property')
  // `computed` is optional
);
```

Which will result in:

```js
object.property
```

However, we said that `object` needed to be an `Expression` so why is `Identifier` valid?

Well if we look at the definition of `Identifier` we can see that it has an `aliases` property which states that it is also an expression.

```js
aliases: ["Expression", "LVal"],
```

So since `MemberExpression` is a type of `Expression`, we could set it as the `object` of another `MemberExpression`:

```js
t.memberExpression(
  t.memberExpression(
    t.identifier('member'),
    t.identifier('expression')
  ),
  t.identifier('property')
)
```

Which will result in:

```js
member.expression.property
```

It's very unlikely that you will ever memorize the builder method signatures for every node type. So you should take some time and understand how they are generated from the node definitions.

You can find all of the actual [definitions here](https://github.com/babel/babel/tree/master/packages/babel-types/src/definitions) and you can see them [documented here](https://github.com/babel/babel/blob/master/doc/ast/spec.md)

* * *

# <a id="toc-best-practices"></a>Best Practices

## <a id="toc-create-helper-builders-and-checkers"></a> Create Helper Builders and Checkers

It's pretty simple to extract certain checks (if a node is a certain type) into their own helper functions as well as extracting out helpers for specific node types.

```js
function isAssignment(node) {
  return node && node.operator === opts.operator + "=";
}

function buildAssignment(left, right) {
  return t.assignmentExpression("=", left, right);
}
```

## <a id="toc-avoid-traversing-the-ast-as-much-as-possible"></a>Avoid traversing the AST as much as possible

Traversing the AST is expensive, and it's easy to accidentally traverse the AST more than necessary. This could be thousands if not tens of thousands of extra operations.

Babel optimizes this as much as possible, merging visitors together if it can in order to do everything in a single traversal.

### <a id="toc-merge-visitors-whenever-possible"></a>Merge visitors whenever possible

When writing visitors, it may be tempting to call `path.traverse` in multiple places where they are logically necessary.

```js
path.traverse({
  Identifier(path) {
    // ...
  }
});

path.traverse({
  BinaryExpression(path) {
    // ...
  }
});
```

However, it is far better to write these as a single visitor that only gets run once. Otherwise you are traversing the same tree multiple times for no reason.

```js
path.traverse({
  Identifier(path) {
    // ...
  },
  BinaryExpression(path) {
    // ...
  }
});
```

### <a id="toc-do-not-traverse-when-manual-lookup-will-do"></a>Do not traverse when manual lookup will do

It may also be tempting to call `path.traverse` when looking for a particular node type.

```js
const nestedVisitor = {
  Identifier(path) {
    // ...
  }
};

const MyVisitor = {
  FunctionDeclaration(path) {
    path.get('params').traverse(nestedVisitor);
  }
};
```

However, if you are looking for something specific and shallow, there is a good chance you can manually lookup the nodes you need without performing a costly traversal.

```js
const MyVisitor = {
  FunctionDeclaration(path) {
    path.node.params.forEach(function() {
      // ...
    });
  }
};
```

## <a id="toc-optimizing-nested-visitors"></a>Optimizing nested visitors

When you are nesting visitors, it might make sense to write them nested in your code.

```js
const MyVisitor = {
  FunctionDeclaration(path) {
    path.traverse({
      Identifier(path) {
        // ...
      }
    });
  }
};
```

However, this creates a new visitor object every time `FunctionDeclaration()` is called. That can be costly, because Babel does some processing each time a new visitor object is passed in (such as exploding keys containing multiple types, performing validation, and adjusting the object structure). Because Babel stores flags on visitor objects indicating that it's already performed that processing, it's better to store the visitor in a variable and pass the same object each time.

```js
const nestedVisitor = {
  Identifier(path) {
    // ...
  }
};

const MyVisitor = {
  FunctionDeclaration(path) {
    path.traverse(nestedVisitor);
  }
};
```

If you need some state within the nested visitor, like so:

```js
const MyVisitor = {
  FunctionDeclaration(path) {
    var exampleState = path.node.params[0].name;

    path.traverse({
      Identifier(path) {
        if (path.node.name === exampleState) {
          // ...
        }
      }
    });
  }
};
```

You can pass it in as state to the `traverse()` method and have access to it on `this` in the visitor.

```js
const nestedVisitor = {
  Identifier(path) {
    if (path.node.name === this.exampleState) {
      // ...
    }
  }
};

const MyVisitor = {
  FunctionDeclaration(path) {
    var exampleState = path.node.params[0].name;
    path.traverse(nestedVisitor, { exampleState });
  }
};
```

## <a id="toc-being-aware-of-nested-structures"></a>Being aware of nested structures

Sometimes when thinking about a given transform, you might forget that the given structure can be nested.

For example, imagine we want to lookup the `constructor` `ClassMethod` from the `Foo` `ClassDeclaration`.

```js
class Foo {
  constructor() {
    // ...
  }
}
```

```js
const constructorVisitor = {
  ClassMethod(path) {
    if (path.node.name === 'constructor') {
      // ...
    }
  }
}

const MyVisitor = {
  ClassDeclaration(path) {
    if (path.node.id.name === 'Foo') {
      path.traverse(constructorVisitor);
    }
  }
}
```

We are ignoring the fact that classes can be nested and using the traversal above we will hit a nested `constructor` as well:

```js
class Foo {
  constructor() {
    class Bar {
      constructor() {
        // ...
      }
    }
  }
}
```

## <a id="toc-unit-testing"></a>Unit Testing

There are a few primary ways to test babel plugins: snapshot tests, AST tests, and exec tests. We'll use [jest](http://facebook.github.io/jest/) for this example because it supports snapshot testing out of the box. The example we're creating here is hosted in [this repo](https://github.com/brigand/babel-plugin-testing-example).

First we need a babel plugin, we'll put this in src/index.js.

```js
<br />module.exports = function testPlugin(babel) {
  return {
    visitor: {
      Identifier(path) {
        if (path.node.name === 'foo') {
          path.node.name = 'bar';
        }
      }
    }
  };
};
```

### Snapshot Tests

Next, install our dependencies with `npm install --save-dev babel-core jest`, and then we can begin writing our first test: the snapshot. Snapshot tests allow us to visually inspect the output of our babel plugin. We give it an input, tell it to make a snapshot, and it saves it to a file. We check in the snapshots into git. This allows us to see when we've affected the output of any of our test cases. It also gives use a diff in pull requests. Of course you could do this with any test framework, but with jest updating the snapshots is as easy as `jest -u`.

```js
// src/__tests__/index-test.js
const babel = require('babel-core');
const plugin = require('../');

var example = `
var foo = 1;
if (foo) console.log(foo);
`;

it('works', () => {
  const {code} = babel.transform(example, {plugins: [plugin]});
  expect(code).toMatchSnapshot();
});
```

This gives us a snapshot file in `src/__tests__/__snapshots__/index-test.js.snap`.

```js
exports[`test works 1`] = `
"
var bar = 1;
if (bar) console.log(bar);"
`;
```

If we change 'bar' to 'baz' in our plugin and run jest again, we get this:

```diff
Received value does not match stored snapshot 1.

    - Snapshot
    + Received

    @@ -1,3 +1,3 @@
     "
    -var bar = 1;
    -if (bar) console.log(bar);"
    +var baz = 1;
    +if (baz) console.log(baz);"
```

We see how our change to the plugin code affected the output of our plugin, and if the output looks good to us, we can run `jest -u` to update the snapshot.

### AST Tests

In addition to snapshot testing, we can manually inspect the AST. This is a simple but brittle example. For more involved situations you may wish to leverage babel-traverse. It allows you to specify an object with a `visitor` key, exactly like you use for the plugin itself.

```js
it('contains baz', () => {
  const {ast} = babel.transform(example, {plugins: [plugin]});
  const program = ast.program;
  const declaration = program.body[0].declarations[0];
  assert.equal(declaration.id.name, 'baz');
  // or babelTraverse(program, {visitor: ...})
});
```

### Exec Tests

Here we'll be transforming the code, and then evaluating that it behaves correctly. Note that we're not using `assert` in the test. This ensures that if our plugin does weird stuff like removing the assert line by accident, the test will still fail.

```js
it('foo is an alias to baz', () => {
  var input = `
    var foo = 1;
    // test that foo was renamed to baz
    var res = baz;
  `;
  var {code} = babel.transform(input, {plugins: [plugin]});
  var f = new Function(`
    ${code};
    return res;
  `);
  var res = f();
  assert(res === 1, 'res is 1');
});
```

Babel core uses a [similar approach](https://github.com/babel/babel/blob/7.0/CONTRIBUTING.md#writing-tests) to snapshot and exec tests.

### [`babel-plugin-tester`](https://github.com/kentcdodds/babel-plugin-tester)

This package makes testing plugins easier. If you're familiar with ESLint's [RuleTester](http://eslint.org/docs/developer-guide/working-with-rules#rule-unit-tests) this should be familiar. You can look at [the docs](https://github.com/kentcdodds/babel-plugin-tester/blob/master/README.md) to get a full sense of what's possible, but here's a simple example:

```js
import pluginTester from 'babel-plugin-tester';
import identifierReversePlugin from '../identifier-reverse-plugin';

pluginTester({
  plugin: identifierReversePlugin,
  fixtures: path.join(__dirname, '__fixtures__'),
  tests: {
    'does not change code with no identifiers': '"hello";',
    'changes this code': {
      code: 'var hello = "hi";',
      output: 'var olleh = "hi";',
    },
    'using fixtures files': {
      fixture: 'changed.js',
      outputFixture: 'changed-output.js',
    },
    'using jest snapshots': {
      code: `
        function sayHi(person) {
          return 'Hello ' + person + '!'
        }
      `,
      snapshot: true,
    },
  },
});
```

* * *

> ***For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) and [@babeljs](https://twitter.com/babeljs) on Twitter.***

================================================
FILE: translations/af/user-handbook.md
================================================
# Babel User Handbook

This document covers everything you ever wanted to know about using [Babel](https://babeljs.io) and related tooling.

[![cc-by-4.0](https://licensebuttons.net/l/by/4.0/80x15.png)](http://creativecommons.org/licenses/by/4.0/)

This handbook is available in other languages, see the [README](/README.md) for a complete list.

# Table of Contents

  * [Introduction](#toc-introduction)
  * [Setting up Babel](#toc-setting-up-babel) 
      * [`babel-cli`](#toc-babel-cli)
      * [Running Babel CLI from within a project](#toc-running-babel-cli-from-within-a-project)
      * [`babel-register`](#toc-babel-register)
      * [`babel-node`](#toc-babel-node)
      * [`babel-core`](#toc-babel-core)
  * [Configuring Babel](#toc-configuring-babel) 
      * [`.babelrc`](#toc-babelrc)
      * [`babel-preset-es2015`](#toc-babel-preset-es2015)
      * [`babel-preset-react`](#toc-babel-preset-react)
      * [`babel-preset-stage-x`](#toc-babel-preset-stage-x)
  * [Executing Babel-generated code](#toc-executing-babel-generated-code) 
      * [`babel-polyfill`](#toc-babel-polyfill)
      * [`babel-runtime`](#toc-babel-runtime)
  * [Configuring Babel (Advanced)](#toc-configuring-babel-advanced) 
      * [Manually specifying plugins](#toc-manually-specifying-plugins)
      * [Plugin options](#toc-plugin-options)
      * [Customizing Babel based on environment](#toc-customizing-babel-based-on-environment)
      * [Making your own preset](#toc-making-your-own-preset)
  * [Babel and other tools](#toc-babel-and-other-tools) 
      * [Static analysis tools](#toc-static-analysis-tools)
      * [Linting](#toc-linting)
      * [Code Style](#toc-code-style)
      * [Documentation](#toc-documentation)
      * [Frameworks](#toc-frameworks)
      * [React](#toc-react)
      * [Text Editors and IDEs](#toc-text-editors-and-ides)
  * [Babel Support](#toc-babel-support) 
      * [Babel Forum](#toc-babel-forum)
      * [Babel Chat](#toc-babel-chat)
      * [Babel Issues](#toc-babel-issues)
      * [Creating an awesome Babel bug report](#toc-creating-an-awesome-babel-bug-report)

# <a id="toc-introduction"></a>Introduction

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.

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.

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.

For example, Babel could transform the new ES2015 arrow function syntax from this:

```js
const square = n => n * n;
```

Into the following:

```js
const square = function square(n) {
  return n * n;
};
```

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.

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.

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

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.

> ***For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) on Twitter.***

* * *

# <a id="toc-setting-up-babel"></a>Setting up Babel

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.

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.

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

## <a id="toc-babel-cli"></a>`babel-cli`

Babel's CLI is a simple way to compile files with Babel from the command line.

Let's first install it globally to learn the basics.

```sh
$ npm install --global babel-cli
```

We can compile our first file like so:

```sh
$ babel my-file.js
```

This will dump the compiled output directly into your terminal. To write it to a file we'll specify an `--out-file` or `-o`.

```sh
$ babel example.js --out-file compiled.js
# or
$ babel example.js -o compiled.js
```

If we want to compile a whole directory into a new directory we can do so using `--out-dir` or `-d`.

```sh
$ babel src --out-dir lib
# or
$ babel src -d lib
```

### <a id="toc-running-babel-cli-from-within-a-project"></a>Running Babel CLI from within a project

While you *can* install Babel CLI globally on your machine, it's much better to install it **locally** project by project.

There are two primary reasons for this.

  1. Different projects on the same machine can depend on different versions of Babel allowing you to update one at a time.
  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.

We can install Babel CLI locally by running:

```sh
$ npm install --save-dev babel-cli
```

> **Note:** Since it's generally a bad idea to run Babel globally you may want to uninstall the global copy by running:
> 
> ```sh
$ npm uninstall --global babel-cli
```

After that finishes installing, your `package.json` file should look like this:

```json
{
  "name": "my-project",
  "version": "1.0.0",
  "devDependencies": {
    "babel-cli": "^6.0.0"
  }
}
```

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.

Simply add a `"scripts"` field to your `package.json` and put the babel command inside there as `build`.

```diff
  {
    "name": "my-project",
    "version": "1.0.0",
+   "scripts": {
+     "build": "babel src -d lib"
+   },
    "devDependencies": {
      "babel-cli": "^6.0.0"
    }
  }
```

Now from our terminal we can run:

```js
npm run build
```

This will run Babel the same way as before, only now we are using a local copy.

## <a id="toc-babel-register"></a>`babel-register`

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.

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.

First let's create an `index.js` file in our project.

```js
console.log("Hello world!");
```

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

First install `babel-register`.

```sh
$ npm install --save-dev babel-register
```

Next, create a `register.js` file in the project and write the following code:

```js
require("babel-register");
require("./index.js");
```

What this does is *registers* Babel in Node's module system and begins compiling every file that is `require`'d.

Now, instead of running `node index.js` we can use `register.js` instead.

```sh
$ node register.js
```

> **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.
> 
> ```js
require("babel-register");
// not compiled:
console.log("Hello world!");
```

## <a id="toc-babel-node"></a>`babel-node`

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.

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.

First make sure that you have `babel-cli` installed.

```sh
$ npm install --save-dev babel-cli
```

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

Then replace wherever you are running `node` with `babel-node`.

If you are using npm `scripts` you can simply do:

```diff
  {
    "scripts": {
-     "script-name": "node script.js"
+     "script-name": "babel-node script.js"
    }
  }
```

Otherwise you'll need to write out the path to `babel-node` itself.

```diff
- node script.js
+ ./node_modules/.bin/babel-node script.js
```

> Tip: You can also use [`npm-run`](https://www.npmjs.com/package/npm-run).

## <a id="toc-babel-core"></a>`babel-core`

If you need to use Babel programmatically for some reason, you can use the `babel-core` package itself.

First install `babel-core`.

```sh
$ npm install babel-core
```

```js
var babel = require("babel-core");
```

If you have a string of JavaScript you can compile it directly using `babel.transform`.

```js
babel.transform("code();", options);
// => { code, map, ast }
```

If you are working with files you can use either the asynchronous api:

```js
babel.transformFile("filename.js", options, function(err, result) {
  result; // => { code, map, ast }
});
```

Or the synchronous api:

```js
babel.transformFileSync("filename.js", options);
// => { code, map, ast }
```

If you already have a Babel AST for whatever reason you may transform from the AST directly.

```js
babel.transformFromAst(ast, code, options);
// => { code, map, ast }
```

For all of the above methods, `options` refers to https://babeljs.io/docs/usage/api/#options.

* * *

# <a id="toc-configuring-babel"></a>Configuring Babel

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.

This is because we haven't told Babel to do anything yet.

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

You can give Babel instructions on what to do by installing **plugins** or **presets** (groups of plugins).

## <a id="toc-babelrc"></a>`.babelrc`

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:

```js
{
  "presets": [],
  "plugins": []
}
```

This file is how you configure Babel to do what you want.

> **Note:** While you can also pass options to Babel in other ways the `.babelrc` file is convention and is the best way.

## <a id="toc-babel-preset-es2015"></a>`babel-preset-es2015`

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

We'll do this by installing the "es2015" Babel preset:

```sh
$ npm install --save-dev babel-preset-es2015
```

Next we'll modify our `.babelrc` to include that preset.

```diff
  {
    "presets": [
+     "es2015"
    ],
    "plugins": []
  }
```

## <a id="toc-babel-preset-react"></a>`babel-preset-react`

Setting up React is just as easy. Just install the preset:

```sh
$ npm install --save-dev babel-preset-react
```

Then add the preset to your `.babelrc` file:

```diff
  {
    "presets": [
      "es2015",
+     "react"
    ],
    "plugins": []
  }
```

## <a id="toc-babel-preset-stage-x"></a>`babel-preset-stage-x`

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.

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.

These are bundled in babel as 4 different presets:

  * `babel-preset-stage-0`
  * `babel-preset-stage-1`
  * `babel-preset-stage-2`
  * `babel-preset-stage-3`

> Note that there is no stage-4 preset as it is simply the `es2015` preset above.

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

Simply install the stage you are interested in using:

```sh
$ npm install --save-dev babel-preset-stage-2
```

Then you can add it to your `.babelrc` config.

```diff
  {
    "presets": [
      "es2015",
      "react",
+     "stage-2"
    ],
    "plugins": []
  }
```

* * *

# <a id="toc-executing-babel-generated-code"></a>Executing Babel-generated code

So you've compiled your code with Babel, but this is not the end of the story.

## <a id="toc-babel-polyfill"></a>`babel-polyfill`

Almost all futuristic JavaScript syntax can be compiled with Babel, but the same is not true for APIs.

For example, the following code has an arrow function that needs to be compiled:

```js
function addAll() {
  return Array.from(arguments).reduce((a, b) => a + b);
}
```

Which turns into this:

```js
function addAll() {
  return Array.from(arguments).reduce(function(a, b) {
    return a + b;
  });
}
```

However, this still won't work everywhere because `Array.from` doesn't exist in every JavaScript environment.

    Uncaught TypeError: Array.from is not a function
    

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.

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.

To include the Babel polyfill, first install it with npm:

```sh
$ npm install --save babel-polyfill
```

Then simply include the polyfill at the top of any file that requires it:

```js
import "babel-polyfill";
```

## <a id="toc-babel-runtime"></a>`babel-runtime`

In order to implement details of ECMAScript specs, Babel will use "helper" methods in order to keep the generated code clean.

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.

Start by installing `babel-plugin-transform-runtime` and `babel-runtime`:

```sh
$ npm install --save-dev babel-plugin-transform-runtime
$ npm install --save babel-runtime
```

Then update your `.babelrc`:

```diff
  {
    "plugins": [
+     "transform-runtime",
      "transform-es2015-classes"
    ]
  }
```

Now Babel will compile code like the following:

```js
class Foo {
  method() {}
}
```

Into this:

```js
import _classCallCheck from "babel-runtime/helpers/classCallCheck";
import _createClass from "babel-runtime/helpers/createClass";

let Foo = function () {
  function Foo() {
    _classCallCheck(this, Foo);
  }

  _createClass(Foo, [{
    key: "method",
    value: function method() {}
  }]);

  return Foo;
}();
```

Rather than putting the `_classCallCheck` and `_createClass` helpers in every single file where they are needed.

* * *

# <a id="toc-configuring-babel-advanced"></a>Configuring Babel (Advanced)

Most people can get by using Babel with just the built-in presets, but Babel exposes much finer-grained power than that.

## <a id="toc-manually-specifying-plugins"></a>Manually specifying plugins

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.

First install a plugin:

```sh
$ npm install --save-dev babel-plugin-transform-es2015-classes
```

Then add the `plugins` field to your `.babelrc`.

```diff
  {
+   "plugins": [
+     "transform-es2015-classes"
+   ]
  }
```

This gives you much finer grained control over the exact transforms you are running.

For a full list of official plugins see the [Babel Plugins page](http://babeljs.io/docs/plugins/).

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

## <a id="toc-plugin-options"></a>Plugin options

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.

To add options to a plugin, simply make the following change:

```diff
  {
    "plugins": [
-     "transform-es2015-classes"
+     ["transform-es2015-classes", { "loose": true }]
    ]
  }
```

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

## <a id="toc-customizing-babel-based-on-environment"></a>Customizing Babel based on environment

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.

For this reason, it is common to want Babel configuration based on the environment. You can do this easily with your `.babelrc` file.

```diff
  {
    "presets": ["es2015"],
    "plugins": [],
+   "env": {
+     "development": {
+       "plugins": [...]
+     },
+     "production": {
+       "plugins": [...]
+     }
    }
  }
```

Babel will enable configuration inside of `env` based on the current environment.

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

**Unix**

```sh
$ BABEL_ENV=production [COMMAND]
$ NODE_ENV=production [COMMAND]
```

**Windows**

```sh
$ SET BABEL_ENV=production
$ [COMMAND]
```

> **Note:** `[COMMAND]` is whatever you use to run Babel (ie. `babel`, `babel-node`, or maybe just `node` if you are using the register hook).
> 
> **Tip:** If you want your command to work across unix and windows platforms then use [`cross-env`](https://www.npmjs.com/package/cross-env).

## <a id="toc-making-your-own-preset"></a>Making your own preset

Manually specifying plugins? Plugin options? Environment-based settings? All this configuration might seem like a ton of repetition for all of your projects.

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

It's easy to create a preset. Say you have this `.babelrc` file:

```js
{
  "presets": [
    "es2015",
    "react"
  ],
  "plugins": [
    "transform-flow-strip-types"
  ]
}
```

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.

First, create a new `package.json` file with the necessary `dependencies` for your preset.

```js
{
  "name": "babel-preset-my-awesome-preset",
  "version": "1.0.0",
  "author": "James Kyle <me@thejameskyle.com>",
  "dependencies": {
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.3.13",
    "babel-plugin-transform-flow-strip-types": "^6.3.15"
  }
}
```

Then create an `index.js` file that exports the contents of your `.babelrc` file, replacing plugin/preset strings with `require` calls.

```js
module.exports = {
  presets: [
    require("babel-preset-es2015"),
    require("babel-preset-react")
  ],
  plugins: [
    require("babel-plugin-transform-flow-strip-types")
  ]
};
```

Then simply publish this to npm and you can use it like you would any preset.

* * *

# <a id="toc-babel-and-other-tools"></a>Babel and other tools

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.

## <a id="toc-static-analysis-tools"></a>Static analysis tools

Newer standards bring a lot of new syntax to the language and static analysis tools are just starting to take advantage of it.

### <a id="toc-linting"></a>Linting

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.

First install `eslint` and `babel-eslint`.

```sh
$ npm install --save-dev eslint babel-eslint
```

Next create or use the existing `.eslintrc` file in your project and set the `parser` as `babel-eslint`.

```diff
  {
+   "parser": "babel-eslint",
    "rules": {
      ...
    }
  }
```

Now add a `lint` task to your npm `package.json` scripts:

```diff
  {
    "name": "my-module",
    "scripts": {
+     "lint": "eslint my-files.js"
    },
    "devDependencies": {
      "babel-eslint": "...",
      "eslint": "..."
    }
  }
```

Then just run the task and you will be all setup.

```sh
$ npm run lint
```

For more information consult the [`babel-eslint`](https://github.com/babel/babel-eslint) or [`eslint`](http://eslint.org) documentation.

### <a id="toc-code-style"></a>Code Style

> JSCS has merged with ESLint, so checkout Code Styling with ESLint.

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.

Even better, this integration now lives within JSCS itself under the `--esnext` option. So integrating Babel is as easy as:

    $ jscs . --esnext
    

From the cli, or adding the `esnext` option to your `.jscsrc` file.

```diff
  {
    "preset": "airbnb",
+   "esnext": true
  }
```

For more information consult the [`babel-jscs`](https://github.com/jscs-dev/babel-jscs) or [`jscs`](http://jscs.info) documentation.

<!--
### Code Coverage

> [WIP]
-->

### <a id="toc-documentation"></a>Documentation

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.

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.

## <a id="toc-frameworks"></a>Frameworks

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.

Frameworks have the opportunity not just to use Babel but to extend it in ways that improve their users' experience.

### <a id="toc-react"></a>React

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

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

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.

<!--
### Ember

> [WIP]
-->

## <a id="toc-text-editors-and-ides"></a>Text Editors and IDEs

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.

  * [Sublime Text](https://github.com/babel/babel-sublime)
  * [Atom](https://atom.io/packages/language-babel)
  * [Vim](https://github.com/jbgutierrez/vim-babel)
  * [WebStorm](https://babeljs.io/docs/setup/#webstorm)

<!--
# Debugging Babel

> [WIP]
-->

* * *

# <a id="toc-babel-support"></a>Babel Support

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.

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.

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.

## <a id="toc-babel-forum"></a>Babel Forum

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

## <a id="toc-babel-chat"></a>Babel Chat

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

<!--
## Babel Stack Overflow

> [WIP]
-->

## <a id="toc-babel-issues"></a>Babel Issues

Babel uses the issue tracker provided by [Github](http://github.com).

You can see all the open and closed issues on [Github](https://github.com/babel/babel/issues).

If you want to open a new issue:

  * [Search for an existing issue](https://github.com/babel/babel/issues)
  * [Create a new bug report](https://github.com/babel/babel/issues/new) or [request a new feature](https://github.com/babel/babel/issues/new)

### <a id="toc-creating-an-awesome-babel-bug-report"></a>Creating an awesome Babel bug report

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.

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.

> [WIP]

* * *

> ***For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) on Twitter.***

================================================
FILE: translations/ar/README.md
================================================
# Babel Handbook

This handbook is divided into two parts:

  * [User Handbook](user-handbook.md) - How to setup/configure Babel and more.
  * [Plugin Handbook](plugin-handbook.md) - How to create plugins for Babel.

> For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) on Twitter.

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

================================================
FILE: translations/ar/plugin-handbook.md
================================================
# Babel Plugin Handbook

This document covers how to create [Babel](https://babeljs.io) [plugins](https://babeljs.io/docs/advanced/plugins/).

[![cc-by-4.0](https://licensebuttons.net/l/by/4.0/80x15.png)](http://creativecommons.org/licenses/by/4.0/)

This handbook is available in other languages, see the [README](/README.md) for a complete list.

# Table of Contents

  * [Introduction](#toc-introduction)
  * [Basics](#toc-basics) 
      * [ASTs](#toc-asts)
      * [Stages of Babel](#toc-stages-of-babel)
      * [Parse](#toc-parse) 
          * [Lexical Analysis](#toc-lexical-analysis)
          * [Syntactic Analysis](#toc-syntactic-analysis)
      * [Transform](#toc-transform)
      * [Generate](#toc-generate)
      * [Traversal](#toc-traversal)
      * [Visitors](#toc-visitors)
      * [Paths](#toc-paths) 
          * [Paths in Visitors](#toc-paths-in-visitors)
      * [State](#toc-state)
      * [Scopes](#toc-scopes) 
          * [Bindings](#toc-bindings)
  * [API](#toc-api) 
      * [babylon](#toc-babylon)
      * [babel-traverse](#toc-babel-traverse)
      * [babel-types](#toc-babel-types)
      * [Definitions](#toc-definitions)
      * [Builders](#toc-builders)
      * [المدقق](#toc-validators)
      * [Converters](#toc-converters)
      * [babel-generator](#toc-babel-generator)
      * [babel-template](#toc-babel-template)
  * [Writing your first Babel Plugin](#toc-writing-your-first-babel-plugin)
  * [Transformation Operations](#toc-transformation-operations) 
      * [Visiting](#toc-visiting)
      * [Get the Path of Sub-Node](#toc-get-the-path-of-a-sub-node)
      * [Check if a node is a certain type](#toc-check-if-a-node-is-a-certain-type)
      * [Check if a path is a certain type](#toc-check-if-a-path-is-a-certain-type)
      * [Check if an identifier is referenced](#toc-check-if-an-identifier-is-referenced)
      * [Find a specific parent path](#toc-find-a-specific-parent-path)
      * [Get Sibling Paths](#toc-get-sibling-paths)
      * [Stopping Traversal](#toc-stopping-traversal)
      * [Manipulation](#toc-manipulation)
      * [Replacing a node](#toc-replacing-a-node)
      * [Replacing a node with multiple nodes](#toc-replacing-a-node-with-multiple-nodes)
      * [Replacing a node with a source string](#toc-replacing-a-node-with-a-source-string)
      * [Inserting a sibling node](#toc-inserting-a-sibling-node)
      * [Inserting into a container](#toc-inserting-into-a-container)
      * [Removing a node](#toc-removing-a-node)
      * [Replacing a parent](#toc-replacing-a-parent)
      * [Removing a parent](#toc-removing-a-parent)
      * [Scope](#toc-scope)
      * [Checking if a local variable is bound](#toc-checking-if-a-local-variable-is-bound)
      * [Generating a UID](#toc-generating-a-uid)
      * [Pushing a variable declaration to a parent scope](#toc-pushing-a-variable-declaration-to-a-parent-scope)
      * [Rename a binding and its references](#toc-rename-a-binding-and-its-references)
  * [Plugin Options](#toc-plugin-options) 
      * [Pre and Post in Plugins](#toc-pre-and-post-in-plugins)
      * [Enabling Syntax in Plugins](#toc-enabling-syntax-in-plugins)
  * [Building Nodes](#toc-building-nodes)
  * [Best Practices](#toc-best-practices) 
      * [Avoid traversing the AST as much as possible](#toc-avoid-traversing-the-ast-as-much-as-possible)
      * [Merge visitors whenever possible](#toc-merge-visitors-whenever-possible)
      * [Do not traverse when manual lookup will do](#toc-do-not-traverse-when-manual-lookup-will-do)
      * [Optimizing nested visitors](#toc-optimizing-nested-visitors)
      * [Being aware of nested structures](#toc-being-aware-of-nested-structures)
      * [Unit Testing](#toc-unit-testing)

# <a id="toc-introduction"></a>Introduction

Babel is a generic multi-purpose compiler for JavaScript. More than that it is a collection of modules that can be used for many different forms of static analysis.

> Static analysis is the process of analyzing code without executing it. (Analysis of code while executing it is known as dynamic analysis). The purpose of static analysis varies greatly. It can be used for linting, compiling, code highlighting, code transformation, optimization, minification, and much more.

You can use Babel to build many different types of tools that can help you be more productive and write better programs.

> ***For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) on Twitter.***

* * *

# <a id="toc-basics"></a>Basics

Babel is a JavaScript compiler, specifically a source-to-source compiler, often called a "transpiler". This means that you give Babel some JavaScript code, Babel modifies the code, and generates the new code back out.

## <a id="toc-asts"></a>ASTs

Each of these steps involve creating or working with an [Abstract Syntax Tree](https://en.wikipedia.org/wiki/Abstract_syntax_tree) or AST.

> Babel uses an AST modified from [ESTree](https://github.com/estree/estree), with the core spec located [here](https://github.com/babel/babylon/blob/master/ast/spec.md).

```js
function square(n) {
  return n * n;
}
```

> Check out [AST Explorer](http://astexplorer.net/) to get a better sense of the AST nodes. [Here](http://astexplorer.net/#/Z1exs6BWMq) is a link to it with the example code above pasted in.

This same program can be represented as a tree like this:

```md
- FunctionDeclaration:
  - id:
    - Identifier:
      - name: square
  - params [1]
    - Identifier
      - name: n
  - body:
    - BlockStatement
      - body [1]
        - ReturnStatement
          - argument
            - BinaryExpression
              - operator: *
              - left
                - Identifier
                  - name: n
              - right
                - Identifier
                  - name: n
```

Or as a JavaScript Object like this:

```js
{
  type: "FunctionDeclaration",
  id: {
    type: "Identifier",
    name: "square"
  },
  params: [{
    type: "Identifier",
    name: "n"
  }],
  body: {
    type: "BlockStatement",
    body: [{
      type: "ReturnStatement",
      argument: {
        type: "BinaryExpression",
        operator: "*",
        left: {
          type: "Identifier",
          name: "n"
        },
        right: {
          type: "Identifier",
          name: "n"
        }
      }
    }]
  }
}
```

You'll notice that each level of the AST has a similar structure:

```js
{
  type: "FunctionDeclaration",
  id: {...},
  params: [...],
  body: {...}
}
```

```js
{
  type: "Identifier",
  name: ...
}
```

```js
{
  type: "BinaryExpression",
  operator: ...,
  left: {...},
  right: {...}
}
```

> Note: Some properties have been removed for simplicity.

Each of these are known as a **Node**. An AST can be made up of a single Node, or hundreds if not thousands of Nodes. Together they are able to describe the syntax of a program that can be used for static analysis.

Every Node has this interface:

```typescript
interface Node {
  type: string;
}
```

The `type` field is a string representing the type of Node the object is (ie. `"FunctionDeclaration"`, `"Identifier"`, or `"BinaryExpression"`). Each type of Node defines an additional set of properties that describe that particular node type.

There are additional properties on every Node that Babel generates which describe the position of the Node in the original source code.

```js
{
  type: ...,
  start: 0,
  end: 38,
  loc: {
    start: {
      line: 1,
      column: 0
    },
    end: {
      line: 3,
      column: 1
    }
  },
  ...
}
```

These properties `start`, `end`, `loc`, appear in every single Node.

## <a id="toc-stages-of-babel"></a>Stages of Babel

The three primary stages of Babel are **parse**, **transform**, **generate**.

### <a id="toc-parse"></a>Parse

The **parse** stage, takes code and outputs an AST. There are two phases of parsing in Babel: [**Lexical Analysis**](https://en.wikipedia.org/wiki/Lexical_analysis) and [**Syntactic Analysis**](https://en.wikipedia.org/wiki/Parsing).

#### <a id="toc-lexical-analysis"></a>Lexical Analysis

Lexical Analysis will take a string of code and turn it into a stream of **tokens**.

You can think of tokens as a flat array of language syntax pieces.

```js
n * n;
```

```js
[
  { type: { ... }, value: "n", start: 0, end: 1, loc: { ... } },
  { type: { ... }, value: "*", start: 2, end: 3, loc: { ... } },
  { type: { ... }, value: "n", start: 4, end: 5, loc: { ... } },
  ...
]
```

Each of the `type`s here have a set of properties describing the token:

```js
{
  type: {
    label: 'name',
    keyword: undefined,
    beforeExpr: false,
    startsExpr: true,
    rightAssociative: false,
    isLoop: false,
    isAssign: false,
    prefix: false,
    postfix: false,
    binop: null,
    updateContext: null
  },
  ...
}
```

Like AST nodes they also have a `start`, `end`, and `loc`.

#### <a id="toc-syntactic-analysis"></a>Syntactic Analysis

Syntactic Analysis will take a stream of tokens and turn it into an AST representation. Using the information in the tokens, this phase will reformat them as an AST which represents the structure of the code in a way that makes it easier to work with.

### <a id="toc-transform"></a>Transform

The [transform](https://en.wikipedia.org/wiki/Program_transformation) stage takes an AST and traverses through it, adding, updating, and removing nodes as it goes along. This is by far the most complex part of Babel or any compiler. This is where plugins operate and so it will be the subject of most of this handbook. So we won't dive too deep right now.

### <a id="toc-generate"></a>Generate

The [code generation](https://en.wikipedia.org/wiki/Code_generation_(compiler)) stage takes the final AST and turns it back into a string of code, also creating [source maps](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/).

Code generation is pretty simple: you traverse through the AST depth-first, building a string that represents the transformed code.

## <a id="toc-traversal"></a>Traversal

When you want to transform an AST you have to [traverse the tree](https://en.wikipedia.org/wiki/Tree_traversal) recursively.

Say we have the type `FunctionDeclaration`. It has a few properties: `id`, `params`, and `body`. Each of them have nested nodes.

```js
{
  type: "FunctionDeclaration",
  id: {
    type: "Identifier",
    name: "square"
  },
  params: [{
    type: "Identifier",
    name: "n"
  }],
  body: {
    type: "BlockStatement",
    body: [{
      type: "ReturnStatement",
      argument: {
        type: "BinaryExpression",
        operator: "*",
        left: {
          type: "Identifier",
          name: "n"
        },
        right: {
          type: "Identifier",
          name: "n"
        }
      }
    }]
  }
}
```

So we start at the `FunctionDeclaration` and we know its internal properties so we visit each of them and their children in order.

Next we go to `id` which is an `Identifier`. `Identifier`s don't have any child node properties so we move on.

After that is `params` which is an array of nodes so we visit each of them. In this case it's a single node which is also an `Identifier` so we move on.

Then we hit `body` which is a `BlockStatement` with a property `body` that is an array of Nodes so we go to each of them.

The only item here is a `ReturnStatement` node which has an `argument`, we go to the `argument` and find a `BinaryExpression`.

The `BinaryExpression` has an `operator`, a `left`, and a `right`. The operator isn't a node, just a value, so we don't go to it, and instead just visit `left` and `right`.

This traversal process happens throughout the Babel transform stage.

### <a id="toc-visitors"></a>Visitors

When we talk about "going" to a node, we actually mean we are **visiting** them. The reason we use that term is because there is this concept of a [**visitor**](https://en.wikipedia.org/wiki/Visitor_pattern).

Visitors are a pattern used in AST traversal across languages. Simply put they are an object with methods defined for accepting particular node types in a tree. That's a bit abstract so let's look at an example.

```js
const MyVisitor = {
  Identifier() {
    console.log("Called!");
  }
};

// You can also create a visitor and add methods on it later
let visitor = {};
visitor.MemberExpression = function() {};
visitor.FunctionDeclaration = function() {}
```

> **Note:** `Identifier() { ... }` is shorthand for `Identifier: { enter() { ... } }`.

This is a basic visitor that when used during a traversal will call the `Identifier()` method for every `Identifier` in the tree.

So with this code the `Identifier()` method will be called four times with each `Identifier` (including `square`).

```js
function square(n) {
  return n * n;
}
```

```js
path.traverse(MyVisitor);
Called!
Called!
Called!
Called!
```

These calls are all on node **enter**. However there is also the possibility of calling a visitor method when on **exit**.

Imagine we have this tree structure:

```js
- FunctionDeclaration
  - Identifier (id)
  - Identifier (params[0])
  - BlockStatement (body)
    - ReturnStatement (body)
      - BinaryExpression (argument)
        - Identifier (left)
        - Identifier (right)
```

As we traverse down each branch of the tree we eventually hit dead ends where we need to traverse back up the tree to get to the next node. Going down the tree we **enter** each node, then going back up we **exit** each node.

Let's *walk* through what this process looks like for the above tree.

  * Enter `FunctionDeclaration` 
      * Enter `Identifier (id)`
      * Hit dead end
      * Exit `Identifier (id)`
      * Enter `Identifier (params[0])`
      * Hit dead end
      * Exit `Identifier (params[0])`
      * Enter `BlockStatement (body)`
      * Enter `ReturnStatement (body)` 
          * Enter `BinaryExpression (argument)`
          * Enter `Identifier (left)` 
              * Hit dead end
          * Exit `Identifier (left)`
          * Enter `Identifier (right)` 
              * Hit dead end
          * Exit `Identifier (right)`
          * Exit `BinaryExpression (argument)`
      * Exit `ReturnStatement (body)`
      * Exit `BlockStatement (body)`
  * Exit `FunctionDeclaration`

So when creating a visitor you have two opportunities to visit a node.

```js
const MyVisitor = {
  Identifier: {
    enter() {
      console.log("Entered!");
    },
    exit() {
      console.log("Exited!");
    }
  }
};
```

If necessary, you can also apply the same function for multiple visitor nodes by separating them with a `|` in the method name as a string like `Identifier|MemberExpression`.

Example usage in the [flow-comments](https://github.com/babel/babel/blob/2b6ff53459d97218b0cf16f8a51c14a165db1fd2/packages/babel-plugin-transform-flow-comments/src/index.js#L47) plugin

```js
const MyVisitor = {
  "ExportNamedDeclaration|Flow"(path) {}
};
```

You can also use aliases as visitor nodes (as defined in [babel-types](https://github.com/babel/babel/tree/master/packages/babel-types/src/definitions)).

For example,

`Function` is an alias for `FunctionDeclaration`, `FunctionExpression`, `ArrowFunctionExpression`, `ObjectMethod` and `ClassMethod`.

```js
const MyVisitor = {
  Function(path) {}
};
```

### <a id="toc-paths"></a>Paths

An AST generally has many Nodes, but how do Nodes relate to one another? We could have one giant mutable object that you manipulate and have full access to, or we can simplify this with **Paths**.

A **Path** is an object representation of the link between two nodes.

For example if we take the following node and its child:

```js
{
  type: "FunctionDeclaration",
  id: {
    type: "Identifier",
    name: "square"
  },
  ...
}
```

And represent the child `Identifier` as a path, it looks something like this:

```js
{
  "parent": {
    "type": "FunctionDeclaration",
    "id": {...},
    ....
  },
  "node": {
    "type": "Identifier",
    "name": "square"
  }
}
```

It also has additional metadata about the path:

```js
{
  "parent": {...},
  "node": {...},
  "hub": {...},
  "contexts": [],
  "data": {},
  "shouldSkip": false,
  "shouldStop": false,
  "removed": false,
  "state": null,
  "opts": null,
  "skipKeys": null,
  "parentPath": null,
  "context": null,
  "container": null,
  "listKey": null,
  "inList": false,
  "parentKey": null,
  "key": null,
  "scope": null,
  "type": null,
  "typeAnnotation": null
}
```

As well as tons and tons of methods related to adding, updating, moving, and removing nodes, but we'll get into those later.

In a sense, paths are a **reactive** representation of a node's position in the tree and all sorts of information about the node. Whenever you call a method that modifies the tree, this information is updated. Babel manages all of this for you to make working with nodes easy and as stateless as possible.

#### <a id="toc-paths-in-visitors"></a>Paths in Visitors

When you have a visitor that has a `Identifier()` method, you're actually visiting the path instead of the node. This way you are mostly working with the reactive representation of a node instead of the node itself.

```js
const MyVisitor = {
  Identifier(path) {
    console.log("Visiting: " + path.node.name);
  }
};
```

```js
a + b + c;
```

```js
path.traverse(MyVisitor);
Visiting: a
Visiting: b
Visiting: c
```

### <a id="toc-state"></a>State

State is the enemy of AST transformation. State will bite you over and over again and your assumptions about state will almost always be proven wrong by some syntax that you didn't consider.

Take the following code:

```js
function square(n) {
  return n * n;
}
```

Let's write a quick hacky visitor that will rename `n` to `x`.

```js
let paramName;

const MyVisitor = {
  FunctionDeclaration(path) {
    const param = path.node.params[0];
    paramName = param.name;
    param.name = "x";
  },

  Identifier(path) {
    if (path.node.name === paramName) {
      path.node.name = "x";
    }
  }
};
```

This might work for the above code, but we can easily break that by doing this:

```js
function square(n) {
  return n * n;
}
n;
```

The better way to deal with this is recursion. So let's make like a Christopher Nolan film and put a visitor inside of a visitor.

```js
const updateParamNameVisitor = {
  Identifier(path) {
    if (path.node.name === this.paramName) {
      path.node.name = "x";
    }
  }
};

const MyVisitor = {
  FunctionDeclaration(path) {
    const param = path.node.params[0];
    const paramName = param.name;
    param.name = "x";

    path.traverse(updateParamNameVisitor, { paramName });
  }
};

path.traverse(MyVisitor);
```

Of course, this is a contrived example but it demonstrates how to eliminate global state from your visitors.

### <a id="toc-scopes"></a>Scopes

Next let's introduce the concept of a [**scope**](https://en.wikipedia.org/wiki/Scope_(computer_science)). JavaScript has [lexical scoping](https://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping_vs._dynamic_scoping), which is a tree structure where blocks create new scope.

```js
// global scope

function scopeOne() {
  // scope 1

  function scopeTwo() {
    // scope 2
  }
}
```

Whenever you create a reference in JavaScript, whether that be by a variable, function, class, param, import, label, etc., it belongs to the current scope.

```js
var global = "I am in the global scope";

function scopeOne() {
  var one = "I am in the scope created by `scopeOne()`";

  function scopeTwo() {
    var two = "I am in the scope created by `scopeTwo()`";
  }
}
```

Code within a deeper scope may use a reference from a higher scope.

```js
function scopeOne() {
  var one = "I am in the scope created by `scopeOne()`";

  function scopeTwo() {
    one = "I am updating the reference in `scopeOne` inside `scopeTwo`";
  }
}
```

A lower scope might also create a reference of the same name without modifying it.

```js
function scopeOne() {
  var one = "I am in the scope created by `scopeOne()`";

  function scopeTwo() {
    var one = "I am creating a new `one` but leaving reference in `scopeOne()` alone.";
  }
}
```

When writing a transform, we want to be wary of scope. We need to make sure we don't break existing code while modifying different parts of it.

We may want to add new references and make sure they don't collide with existing ones. Or maybe we just want to find where a variable is referenced. We want to be able to track these references within a given scope.

A scope can be represented as:

```js
{
  path: path,
  block: path.node,
  parentBlock: path.parent,
  parent: parentScope,
  bindings: [...]
}
```

When you create a new scope you do so by giving it a path and a parent scope. Then during the traversal process it collects all the references ("bindings") within that scope.

Once that's done, there's all sorts of methods you can use on scopes. We'll get into those later though.

#### <a id="toc-bindings"></a>Bindings

References all belong to a particular scope; this relationship is known as a **binding**.

```js
function scopeOnce() {
  var ref = "This is a binding";

  ref; // This is a reference to a binding

  function scopeTwo() {
    ref; // This is a reference to a binding from a lower scope
  }
}
```

A single binding looks like this:

```js
{
  identifier: node,
  scope: scope,
  path: path,
  kind: 'var',

  referenced: true,
  references: 3,
  referencePaths: [path, path, path],

  constant: false,
  constantViolations: [path]
}
```

With this information you can find all the references to a binding, see what type of binding it is (parameter, declaration, etc.), lookup what scope it belongs to, or get a copy of its identifier. You can even tell if it's constant and if not, see what paths are causing it to be non-constant.

Being able to tell if a binding is constant is useful for many purposes, the largest of which is minification.

```js
function scopeOne() {
  var ref1 = "This is a constant binding";

  becauseNothingEverChangesTheValueOf(ref1);

  function scopeTwo() {
    var ref2 = "This is *not* a constant binding";
    ref2 = "Because this changes the value";
  }
}
```

* * *

# <a id="toc-api"></a>API

Babel is actually a collection of modules. In this section we'll walk through the major ones, explaining what they do and how to use them.

> Note: This is not a replacement for detailed API documentation which will be available elsewhere shortly.

## <a id="toc-babylon"></a>[`babylon`](https://github.com/babel/babylon)

Babylon is Babel's parser. Started as a fork of Acorn, it's fast, simple to use, has plugin-based architecture for non-standard features (as well as future standards).

First, let's install it.

```sh
$ npm install --save babylon
```

Let's start by simply parsing a string of code:

```js
import * as babylon from "babylon";

const code = `function square(n) {
  return n * n;
}`;

babylon.parse(code);
// Node {
//   type: "File",
//   start: 0,
//   end: 38,
//   loc: SourceLocation {...},
//   program: Node {...},
//   comments: [],
//   tokens: [...]
// }
```

We can also pass options to `parse()` like so:

```js
babylon.parse(code, {
  sourceType: "module", // default: "script"
  plugins: ["jsx"] // default: []
});
```

`sourceType` can either be `"module"` or `"script"` which is the mode that Babylon should parse in. `"module"` will parse in strict mode and allow module declarations, `"script"` will not.

> **Note:** `sourceType` defaults to `"script"` and will error when it finds `import` or `export`. Pass `sourceType: "module"` to get rid of these errors.

Since Babylon is built with a plugin-based architecture, there is also a `plugins` option which will enable the internal plugins. Note that Babylon has not yet opened this API to external plugins, although may do so in the future.

To see a full list of plugins, see the [Babylon README](https://github.com/babel/babylon/blob/master/README.md#plugins).

## <a id="toc-babel-traverse"></a>[`babel-traverse`](https://github.com/babel/babel/tree/master/packages/babel-traverse)

The Babel Traverse module maintains the overall tree state, and is responsible for replacing, removing, and adding nodes.

Install it by running:

```sh
$ npm install --save babel-traverse
```

We can use it alongside Babylon to traverse and update nodes:

```js
import * as babylon from "babylon";
import traverse from "babel-traverse";

const code = `function square(n) {
  return n * n;
}`;

const ast = babylon.parse(code);

traverse(ast, {
  enter(path) {
    if (
      path.node.type === "Identifier" &&
      path.node.name === "n"
    ) {
      path.node.name = "x";
    }
  }
});
```

## <a id="toc-babel-types"></a>[`babel-types`](https://github.com/babel/babel/tree/master/packages/babel-types)

Babel Types is a Lodash-esque utility library for AST nodes. It contains methods for building, validating, and converting AST nodes. It's useful for cleaning up AST logic with well thought out utility methods.

You can install it by running:

```sh
$ npm install --save babel-types
```

Then start using it:

```js
import traverse from "babel-traverse";
import * as t from "babel-types";

traverse(ast, {
  enter(path) {
    if (t.isIdentifier(path.node, { name: "n" })) {
      path.node.name = "x";
    }
  }
});
```

### <a id="toc-definitions"></a>Definitions

Babel Types has definitions for every single type of node, with information on what properties belong where, what values are valid, how to build that node, how the node should be traversed, and aliases of the Node.

A single node type definition looks like this:

```js
defineType("BinaryExpression", {
  builder: ["operator", "left", "right"],
  fields: {
    operator: {
      validate: assertValueType("string")
    },
    left: {
      validate: assertNodeType("Expression")
    },
    right: {
      validate: assertNodeType("Expression")
    }
  },
  visitor: ["left", "right"],
  aliases: ["Binary", "Expression"]
});
```

### <a id="toc-builders"></a>Builders

You'll notice the above definition for `BinaryExpression` has a field for a `builder`.

```js
builder: ["operator", "left", "right"]
```

This is because each node type gets a builder method, which when used looks like this:

```js
t.binaryExpression("*", t.identifier("a"), t.identifier("b"));
```

Which creates an AST like this:

```js
{
  type: "BinaryExpression",
  operator: "*",
  left: {
    type: "Identifier",
    name: "a"
  },
  right: {
    type: "Identifier",
    name: "b"
  }
}
```

Which when printed looks like this:

```js
a * b
```

Builders will also validate the nodes they are creating and throw descriptive errors if used improperly. Which leads into the next type of method.

### <a id="toc-validators"></a>المدقق

The definition for `BinaryExpression` also includes information on the `fields` of a node and how to validate them.

```js
fields: {
  operator: {
    validate: assertValueType("string")
  },
  left: {
    validate: assertNodeType("Expression")
  },
  right: {
    validate: assertNodeType("Expression")
  }
}
```

This is used to create two types of validating methods. The first of which is `isX`.

```js
t.isBinaryExpression(maybeBinaryExpressionNode);
```

This tests to make sure that the node is a binary expression, but you can also pass a second parameter to ensure that the node contains certain properties and values.

```js
t.isBinaryExpression(maybeBinaryExpressionNode, { operator: "*" });
```

There is also the more, *ehem*, assertive version of these methods, which will throw errors instead of returning `true` or `false`.

```js
t.assertBinaryExpression(maybeBinaryExpressionNode);
t.assertBinaryExpression(maybeBinaryExpressionNode, { operator: "*" });
// Error: Expected type "BinaryExpression" with option { "operator": "*" }
```

### <a id="toc-converters"></a>Converters

> [WIP]

## <a id="toc-babel-generator"></a>[`babel-generator`](https://github.com/babel/babel/tree/master/packages/babel-generator)

Babel Generator is the code generator for Babel. It takes an AST and turns it into code with sourcemaps.

Run the following to install it:

```sh
$ npm install --save babel-generator
```

Then use it

```js
import * as babylon from "babylon";
import generate from "babel-generator";

const code = `function square(n) {
  return n * n;
}`;

const ast = babylon.parse(code);

generate(ast, {}, code);
// {
//   code: "...",
//   map: "..."
// }
```

You can also pass options to `generate()`.

```js
generate(ast, {
  retainLines: false,
  compact: "auto",
  concise: false,
  quotes: "double",
  // ...
}, code);
```

## <a id="toc-babel-template"></a>[`babel-template`](https://github.com/babel/babel/tree/master/packages/babel-template)

Babel Template is another tiny but incredibly useful module. It allows you to write strings of code with placeholders that you can use instead of manually building up a massive AST. In computer science, this capability is called quasiquotes.

```sh
$ npm install --save babel-template
```

```js
import template from "babel-template";
import generate from "babel-generator";
import * as t from "babel-types";

const buildRequire = template(`
  var IMPORT_NAME = require(SOURCE);
`);

const ast = buildRequire({
  IMPORT_NAME: t.identifier("myModule"),
  SOURCE: t.stringLiteral("my-module")
});

console.log(generate(ast).code);
```

```js
var myModule = require("my-module");
```

# <a id="toc-writing-your-first-babel-plugin"></a>Writing your first Babel Plugin

Now that you're familiar with all the basics of Babel, let's tie it together with the plugin API.

Start off with a `function` that gets passed the current [`babel`](https://github.com/babel/babel/tree/master/packages/babel-core) object.

```js
export default function(babel) {
  // plugin contents
}
```

Since you'll be using it so often, you'll likely want to grab just `babel.types` like so:

```js
export default function({ types: t }) {
  // plugin contents
}
```

Then you return an object with a property `visitor` which is the primary visitor for the plugin.

```js
export default function({ types: t }) {
  return {
    visitor: {
      // visitor contents
    }
  };
};
```

Each function in the visitor receives 2 arguments: `path` and `state`

```js
export default function({ types: t }) {
  return {
    visitor: {
      Identifier(path, state) {},
      ASTNodeTypeHere(path, state) {}
    }
  };
};
```

Let's write a quick plugin to show off how it works. Here's our source code:

```js
foo === bar;
```

Or in AST form:

```js
{
  type: "BinaryExpression",
  operator: "===",
  left: {
    type: "Identifier",
    name: "foo"
  },
  right: {
    type: "Identifier",
    name: "bar"
  }
}
```

We'll start off by adding a `BinaryExpression` visitor method.

```js
export default function({ types: t }) {
  return {
    visitor: {
      BinaryExpression(path) {
        // ...
      }
    }
  };
}
```

Then let's narrow it down to just `BinaryExpression`s that are using the `===` operator.

```js
visitor: {
  BinaryExpression(path) {
    if (path.node.operator !== "===") {
      return;
    }

    // ...
  }
}
```

Now let's replace the `left` property with a new identifier:

```js
BinaryExpression(path) {
  if (path.node.operator !== "===") {
    return;
  }

  path.node.left = t.identifier("sebmck");
  // ...
}
```

Already if we run this plugin we would get:

```js
sebmck === bar;
```

Now let's just replace the `right` property.

```js
BinaryExpression(path) {
  if (path.node.operator !== "===") {
    return;
  }

  path.node.left = t.identifier("sebmck");
  path.node.right = t.identifier("dork");
}
```

And now for our final result:

```js
sebmck === dork;
```

Awesome! Our very first Babel plugin.

* * *

# <a id="toc-transformation-operations"></a>Transformation Operations

## <a id="toc-visiting"></a>Visiting

### <a id="toc-get-the-path-of-a-sub-node"></a>Get the Path of Sub-Node

To access an AST node's property you normally access the node and then the property. `path.node.property`

```js
// the BinaryExpression AST node has properties: `left`, `right`, `operator`
BinaryExpression(path) {
  path.node.left;
  path.node.right;
  path.node.operator;
}
```

If you need to access the `path` of that property instead, use the `get` method of a path, passing in the string to the property.

```js
BinaryExpression(path) {
  path.get('left');
}
Program(path) {
  path.get('body.0');
}
```

### <a id="toc-check-if-a-node-is-a-certain-type"></a>Check if a node is a certain type

If you want to check what the type of a node is, the preferred way to do so is:

```js
BinaryExpression(path) {
  if (t.isIdentifier(path.node.left)) {
    // ...
  }
}
```

You can also do a shallow check for properties on that node:

```js
BinaryExpression(path) {
  if (t.isIdentifier(path.node.left, { name: "n" })) {
    // ...
  }
}
```

This is functionally equivalent to:

```js
BinaryExpression(path) {
  if (
    path.node.left != null &&
    path.node.left.type === "Identifier" &&
    path.node.left.name === "n"
  ) {
    // ...
  }
}
```

### <a id="toc-check-if-a-path-is-a-certain-type"></a>Check if a path is a certain type

A path has the same methods for checking the type of a node:

```js
BinaryExpression(path) {
  if (path.get('left').isIdentifier({ name: "n" })) {
    // ...
  }
}
```

is equivalent to doing:

```js
BinaryExpression(path) {
  if (t.isIdentifier(path.node.left, { name: "n" })) {
    // ...
  }
}
```

### <a id="toc-check-if-an-identifier-is-referenced"></a>Check if an identifier is referenced

```js
Identifier(path) {
  if (path.isReferencedIdentifier()) {
    // ...
  }
}
```

Alternatively:

```js
Identifier(path) {
  if (t.isReferenced(path.node, path.parent)) {
    // ...
  }
}
```

### <a id="toc-find-a-specific-parent-path"></a>Find a specific parent path

Sometimes you will need to traverse the tree upwards from a path until a condition is satisfied.

Call the provided `callback` with the `NodePath`s of all the parents. When the `callback` returns a truthy value, we return that `NodePath`.

```js
path.findParent((path) => path.isObjectExpression());
```

If the current path should be included as well:

```js
path.find((path) => path.isObjectExpression());
```

Find the closest parent function or program:

```js
path.getFunctionParent();
```

Walk up the tree until we hit a parent node path in a list

```js
path.getStatementParent();
```

### <a id="toc-get-sibling-paths"></a>Get Sibling Paths

If a path is in a list like in the body of a `Function`/`Program`, it will have "siblings".

  * Check if a path is part of a list with `path.inList`
  * You can get the surrounding siblings with `path.getSibling(index)`,
  * The current path's index in the container with `path.key`,
  * The path's container (an array of all sibling nodes) with `path.container`
  * Get the name of the key of the list container with `path.listKey`

> These APIs are used in the [transform-merge-sibling-variables](https://github.com/babel/babili/blob/master/packages/babel-plugin-transform-merge-sibling-variables/src/index.js) plugin used in [babel-minify](https://github.com/babel/babili).

```js
var a = 1; // pathA, path.key = 0
var b = 2; // pathB, path.key = 1
var c = 3; // pathC, path.key = 2
```

```js
export default function({ types: t }) {
  return {
    visitor: {
      VariableDeclaration(path) {
        // if the current path is pathA
        path.inList // true
        path.listKey // "body"
        path.key // 0
        path.getSibling(0) // pathA
        path.getSibling(path.key + 1) // pathB
        path.container // [pathA, pathB, pathC]
      }
    }
  };
}
```

### <a id="toc-stopping-traversal"></a>Stopping Traversal

If your plugin needs to not run in a certain situation, the simpliest thing to do is to write an early return.

```js
BinaryExpression(path) {
  if (path.node.operator !== '**') return;
}
```

If you are doing a sub-traversal in a top level path, you can use 2 provided API methods:

`path.skip()` skips traversing the children of the current path. `path.stop()` stops traversal entirely.

```js
outerPath.traverse({
  Function(innerPath) {
    innerPath.skip(); // if checking the children is irrelevant
  },
  ReferencedIdentifier(innerPath, state) {
    state.iife = true;
    innerPath.stop(); // if you want to save some state and then stop traversal, or deopt
  }
});
```

## <a id="toc-manipulation"></a>Manipulation

### <a id="toc-replacing-a-node"></a>Replacing a node

```js
BinaryExpression(path) {
  path.replaceWith(
    t.binaryExpression("**", path.node.left, t.numberLiteral(2))
  );
}
```

```diff
  function square(n) {
-   return n * n;
+   return n ** 2;
  }
```

### <a id="toc-replacing-a-node-with-multiple-nodes"></a>Replacing a node with multiple nodes

```js
ReturnStatement(path) {
  path.replaceWithMultiple([
    t.expressionStatement(t.stringLiteral("Is this the real life?")),
    t.expressionStatement(t.stringLiteral("Is this just fantasy?")),
    t.expressionStatement(t.stringLiteral("(Enjoy singing the rest of the song in your head)")),
  ]);
}
```

```diff
  function square(n) {
-   return n * n;
+   "Is this the real life?";
+   "Is this just fantasy?";
+   "(Enjoy singing the rest of the song in your head)";
  }
```

> **Note:** When replacing an expression with multiple nodes, they must be statements. This is because Babel uses heuristics extensively when replacing nodes which means that you can do some pretty crazy transformations that would be extremely verbose otherwise.

### <a id="toc-replacing-a-node-with-a-source-string"></a>Replacing a node with a source string

```js
FunctionDeclaration(path) {
  path.replaceWithSourceString(`function add(a, b) {
    return a + b;
  }`);
}
```

```diff
- function square(n) {
-   return n * n;
+ function add(a, b) {
+   return a + b;
  }
```

> **Note:** It's not recommended to use this API unless you're dealing with dynamic source strings, otherwise it's more efficient to parse the code outside of the visitor.

### <a id="toc-inserting-a-sibling-node"></a>Inserting a sibling node

```js
FunctionDeclaration(path) {
  path.insertBefore(t.expressionStatement(t.stringLiteral("Because I'm easy come, easy go.")));
  path.insertAfter(t.expressionStatement(t.stringLiteral("A little high, little low.")));
}
```

```diff
+ "Because I'm easy come, easy go.";
  function square(n) {
    return n * n;
  }
+ "A little high, little low.";
```

> **Note:** This should always be a statement or an array of statements. This uses the same heuristics mentioned in [Replacing a node with multiple nodes](#replacing-a-node-with-multiple-nodes).

### <a id="toc-inserting-into-a-container"></a>Inserting into a container

If you want to insert into a AST node property like that is an array like `body`. It is similar to `insertBefore`/`insertAfter` other than you having to specify the `listKey` which is usually `body`.

```js
ClassMethod(path) {
  path.get('body').unshiftContainer('body', t.expressionStatement(t.stringLiteral('before')));
  path.get('body').pushContainer('body', t.expressionStatement(t.stringLiteral('after')));
}
```

```diff
 class A {
  constructor() {
+   "before"
    var a = 'middle';
+   "after"
  }
 }
```

### <a id="toc-removing-a-node"></a>Removing a node

```js
FunctionDeclaration(path) {
  path.remove();
}
```

```diff
- function square(n) {
-   return n * n;
- }
```

### <a id="toc-replacing-a-parent"></a>Replacing a parent

Just call `replaceWith` with the parentPath: `path.parentPath`

```js
BinaryExpression(path) {
  path.parentPath.replaceWith(
    t.expressionStatement(t.stringLiteral("Anyway the wind blows, doesn't really matter to me, to me."))
  );
}
```

```diff
  function square(n) {
-   return n * n;
+   "Anyway the wind blows, doesn't really matter to me, to me.";
  }
```

### <a id="toc-removing-a-parent"></a>Removing a parent

```js
BinaryExpression(path) {
  path.parentPath.remove();
}
```

```diff
  function square(n) {
-   return n * n;
  }
```

## <a id="toc-scope"></a>Scope

### <a id="toc-checking-if-a-local-variable-is-bound"></a>Checking if a local variable is bound

```js
FunctionDeclaration(path) {
  if (path.scope.hasBinding("n")) {
    // ...
  }
}
```

This will walk up the scope tree and check for that particular binding.

You can also check if a scope has its **own** binding:

```js
FunctionDeclaration(path) {
  if (path.scope.hasOwnBinding("n")) {
    // ...
  }
}
```

### <a id="toc-generating-a-uid"></a>Generating a UID

This will generate an identifier that doesn't collide with any locally defined variables.

```js
FunctionDeclaration(path) {
  path.scope.generateUidIdentifier("uid");
  // Node { type: "Identifier", name: "_uid" }
  path.scope.generateUidIdentifier("uid");
  // Node { type: "Identifier", name: "_uid2" }
}
```

### <a id="toc-pushing-a-variable-declaration-to-a-parent-scope"></a>Pushing a variable declaration to a parent scope

Sometimes you may want to push a `VariableDeclaration` so you can assign to it.

```js
FunctionDeclaration(path) {
  const id = path.scope.generateUidIdentifierBasedOnNode(path.node.id);
  path.remove();
  path.scope.parent.push({ id, init: path.node });
}
```

```diff
- function square(n) {
+ var _square = function square(n) {
    return n * n;
- }
+ };
```

### <a id="toc-rename-a-binding-and-its-references"></a>Rename a binding and its references

```js
FunctionDeclaration(path) {
  path.scope.rename("n", "x");
}
```

```diff
- function square(n) {
-   return n * n;
+ function square(x) {
+   return x * x;
  }
```

Alternatively, you can rename a binding to a generated unique identifier:

```js
FunctionDeclaration(path) {
  path.scope.rename("n");
}
```

```diff
- function square(n) {
-   return n * n;
+ function square(_n) {
+   return _n * _n;
  }
```

* * *

# <a id="toc-plugin-options"></a>Plugin Options

If you would like to let your users customize the behavior of your Babel plugin you can accept plugin specific options which users can specify like this:

```js
{
  plugins: [
    ["my-plugin", {
      "option1": true,
      "option2": false
    }]
  ]
}
```

These options then get passed into plugin visitors through the `state` object:

```js
export default function({ types: t }) {
  return {
    visitor: {
      FunctionDeclaration(path, state) {
        console.log(state.opts);
        // { option1: true, option2: false }
      }
    }
  }
}
```

These options are plugin-specific and you cannot access options from other plugins.

## <a id="toc-pre-and-post-in-plugins"></a> Pre and Post in Plugins

Plugins can have functions that are run before or after plugins. They can be used for setup or cleanup/analysis purposes.

```js
export default function({ types: t }) {
  return {
    pre(state) {
      this.cache = new Map();
    },
    visitor: {
      StringLiteral(path) {
        this.cache.set(path.node.value, 1);
      }
    },
    post(state) {
      console.log(this.cache);
    }
  };
}
```

## <a id="toc-enabling-syntax-in-plugins"></a> Enabling Syntax in Plugins

Plugins can enable [babylon plugins](https://github.com/babel/babylon#plugins) so that users don't need to install/enable them. This prevents a parsing error without inheriting the syntax plugin.

```js
export default function({ types: t }) {
  return {
    inherits: require("babel-plugin-syntax-jsx")
  };
}
```

## <a id="toc-throwing-a-syntax-error"></a> Throwing a Syntax Error

If you want to throw an error with babel-code-frame and a message:

```js
export default function({ types: t }) {
  return {
    visitor: {
      StringLiteral(path) {
        throw path.buildCodeFrameError("Error message here");
      }
    }
  };
}
```

The error looks like:

    file.js: Error message here
       7 |
       8 | let tips = [
    >  9 |   "Click on any AST node with a '+' to expand it",
         |   ^
      10 |
      11 |   "Hovering over a node highlights the \
      12 |    corresponding part in the source code",
    

* * *

# <a id="toc-building-nodes"></a>Building Nodes

When writing transformations you'll often want to build up some nodes to insert into the AST. As mentioned previously, you can do this using the [builder](#builders) methods in the [`babel-types`](#babel-types) package.

The method name for a builder is simply the name of the node type you want to build except with the first letter lowercased. For example if you wanted to build a `MemberExpression` you would use `t.memberExpression(...)`.

The arguments of these builders are decided by the node definition. There's some work that's being done to generate easy-to-read documentation on the definitions, but for now they can all be found [here](https://github.com/babel/babel/tree/master/packages/babel-types/src/definitions).

A node definition looks like the following:

```js
defineType("MemberExpression", {
  builder: ["object", "property", "computed"],
  visitor: ["object", "property"],
  aliases: ["Expression", "LVal"],
  fields: {
    object: {
      validate: assertNodeType("Expression")
    },
    property: {
      validate(node, key, val) {
        let expectedType = node.computed ? "Expression" : "Identifier";
        assertNodeType(expectedType)(node, key, val);
      }
    },
    computed: {
      default: false
    }
  }
});
```

Here you can see all the information about this particular node type, including how to build it, traverse it, and validate it.

By looking at the `builder` property, you can see the 3 arguments that will be needed to call the builder method (`t.memberExpression`).

```js
builder: ["object", "property", "computed"],
```

> Note that sometimes there are more properties that you can customize on the node than the `builder` array contains. This is to keep the builder from having too many arguments. In these cases you need to set the properties manually. An example of this is [`ClassMethod`](https://github.com/babel/babel/blob/bbd14f88c4eea88fa584dd877759dd6b900bf35e/packages/babel-types/src/definitions/es2015.js#L238-L276).

```js
// Example
// because the builder doesn't contain `async` as a property
var node = t.classMethod(
  "constructor",
  t.identifier("constructor"),
  params,
  body
)
// set it manually after creation
node.async = true;
```

You can see the validation for the builder arguments with the `fields` object.

```js
fields: {
  object: {
    validate: assertNodeType("Expression")
  },
  property: {
    validate(node, key, val) {
      let expectedType = node.computed ? "Expression" : "Identifier";
      assertNodeType(expectedType)(node, key, val);
    }
  },
  computed: {
    default: false
  }
}
```

You can see that `object` needs to be an `Expression`, `property` either needs to be an `Expression` or an `Identifier` depending on if the member expression is `computed` or not and `computed` is simply a boolean that defaults to `false`.

So we can construct a `MemberExpression` by doing the following:

```js
t.memberExpression(
  t.identifier('object'),
  t.identifier('property')
  // `computed` is optional
);
```

Which will result in:

```js
object.property
```

However, we said that `object` needed to be an `Expression` so why is `Identifier` valid?

Well if we look at the definition of `Identifier` we can see that it has an `aliases` property which states that it is also an expression.

```js
aliases: ["Expression", "LVal"],
```

So since `MemberExpression` is a type of `Expression`, we could set it as the `object` of another `MemberExpression`:

```js
t.memberExpression(
  t.memberExpression(
    t.identifier('member'),
    t.identifier('expression')
  ),
  t.identifier('property')
)
```

Which will result in:

```js
member.expression.property
```

It's very unlikely that you will ever memorize the builder method signatures for every node type. So you should take some time and understand how they are generated from the node definitions.

You can find all of the actual [definitions here](https://github.com/babel/babel/tree/master/packages/babel-types/src/definitions) and you can see them [documented here](https://github.com/babel/babel/blob/master/doc/ast/spec.md)

* * *

# <a id="toc-best-practices"></a>Best Practices

## <a id="toc-create-helper-builders-and-checkers"></a> Create Helper Builders and Checkers

It's pretty simple to extract certain checks (if a node is a certain type) into their own helper functions as well as extracting out helpers for specific node types.

```js
function isAssignment(node) {
  return node && node.operator === opts.operator + "=";
}

function buildAssignment(left, right) {
  return t.assignmentExpression("=", left, right);
}
```

## <a id="toc-avoid-traversing-the-ast-as-much-as-possible"></a>Avoid traversing the AST as much as possible

Traversing the AST is expensive, and it's easy to accidentally traverse the AST more than necessary. This could be thousands if not tens of thousands of extra operations.

Babel optimizes this as much as possible, merging visitors together if it can in order to do everything in a single traversal.

### <a id="toc-merge-visitors-whenever-possible"></a>Merge visitors whenever possible

When writing visitors, it may be tempting to call `path.traverse` in multiple places where they are logically necessary.

```js
path.traverse({
  Identifier(path) {
    // ...
  }
});

path.traverse({
  BinaryExpression(path) {
    // ...
  }
});
```

However, it is far better to write these as a single visitor that only gets run once. Otherwise you are traversing the same tree multiple times for no reason.

```js
path.traverse({
  Identifier(path) {
    // ...
  },
  BinaryExpression(path) {
    // ...
  }
});
```

### <a id="toc-do-not-traverse-when-manual-lookup-will-do"></a>Do not traverse when manual lookup will do

It may also be tempting to call `path.traverse` when looking for a particular node type.

```js
const nestedVisitor = {
  Identifier(path) {
    // ...
  }
};

const MyVisitor = {
  FunctionDeclaration(path) {
    path.get('params').traverse(nestedVisitor);
  }
};
```

However, if you are looking for something specific and shallow, there is a good chance you can manually lookup the nodes you need without performing a costly traversal.

```js
const MyVisitor = {
  FunctionDeclaration(path) {
    path.node.params.forEach(function() {
      // ...
    });
  }
};
```

## <a id="toc-optimizing-nested-visitors"></a>Optimizing nested visitors

When you are nesting visitors, it might make sense to write them nested in your code.

```js
const MyVisitor = {
  FunctionDeclaration(path) {
    path.traverse({
      Identifier(path) {
        // ...
      }
    });
  }
};
```

However, this creates a new visitor object every time `FunctionDeclaration()` is called. That can be costly, because Babel does some processing each time a new visitor object is passed in (such as exploding keys containing multiple types, performing validation, and adjusting the object structure). Because Babel stores flags on visitor objects indicating that it's already performed that processing, it's better to store the visitor in a variable and pass the same object each time.

```js
const nestedVisitor = {
  Identifier(path) {
    // ...
  }
};

const MyVisitor = {
  FunctionDeclaration(path) {
    path.traverse(nestedVisitor);
  }
};
```

If you need some state within the nested visitor, like so:

```js
const MyVisitor = {
  FunctionDeclaration(path) {
    var exampleState = path.node.params[0].name;

    path.traverse({
      Identifier(path) {
        if (path.node.name === exampleState) {
          // ...
        }
      }
    });
  }
};
```

You can pass it in as state to the `traverse()` method and have access to it on `this` in the visitor.

```js
const nestedVisitor = {
  Identifier(path) {
    if (path.node.name === this.exampleState) {
      // ...
    }
  }
};

const MyVisitor = {
  FunctionDeclaration(path) {
    var exampleState = path.node.params[0].name;
    path.traverse(nestedVisitor, { exampleState });
  }
};
```

## <a id="toc-being-aware-of-nested-structures"></a>Being aware of nested structures

Sometimes when thinking about a given transform, you might forget that the given structure can be nested.

For example, imagine we want to lookup the `constructor` `ClassMethod` from the `Foo` `ClassDeclaration`.

```js
class Foo {
  constructor() {
    // ...
  }
}
```

```js
const constructorVisitor = {
  ClassMethod(path) {
    if (path.node.name === 'constructor') {
      // ...
    }
  }
}

const MyVisitor = {
  ClassDeclaration(path) {
    if (path.node.id.name === 'Foo') {
      path.traverse(constructorVisitor);
    }
  }
}
```

We are ignoring the fact that classes can be nested and using the traversal above we will hit a nested `constructor` as well:

```js
class Foo {
  constructor() {
    class Bar {
      constructor() {
        // ...
      }
    }
  }
}
```

## <a id="toc-unit-testing"></a>Unit Testing

There are a few primary ways to test babel plugins: snapshot tests, AST tests, and exec tests. We'll use [jest](http://facebook.github.io/jest/) for this example because it supports snapshot testing out of the box. The example we're creating here is hosted in [this repo](https://github.com/brigand/babel-plugin-testing-example).

First we need a babel plugin, we'll put this in src/index.js.

```js
<br />module.exports = function testPlugin(babel) {
  return {
    visitor: {
      Identifier(path) {
        if (path.node.name === 'foo') {
          path.node.name = 'bar';
        }
      }
    }
  };
};
```

### Snapshot Tests

Next, install our dependencies with `npm install --save-dev babel-core jest`, and then we can begin writing our first test: the snapshot. Snapshot tests allow us to visually inspect the output of our babel plugin. We give it an input, tell it to make a snapshot, and it saves it to a file. We check in the snapshots into git. This allows us to see when we've affected the output of any of our test cases. It also gives use a diff in pull requests. Of course you could do this with any test framework, but with jest updating the snapshots is as easy as `jest -u`.

```js
// src/__tests__/index-test.js
const babel = require('babel-core');
const plugin = require('../');

var example = `
var foo = 1;
if (foo) console.log(foo);
`;

it('works', () => {
  const {code} = babel.transform(example, {plugins: [plugin]});
  expect(code).toMatchSnapshot();
});
```

This gives us a snapshot file in `src/__tests__/__snapshots__/index-test.js.snap`.

```js
exports[`test works 1`] = `
"
var bar = 1;
if (bar) console.log(bar);"
`;
```

If we change 'bar' to 'baz' in our plugin and run jest again, we get this:

```diff
Received value does not match stored snapshot 1.

    - Snapshot
    + Received

    @@ -1,3 +1,3 @@
     "
    -var bar = 1;
    -if (bar) console.log(bar);"
    +var baz = 1;
    +if (baz) console.log(baz);"
```

We see how our change to the plugin code affected the output of our plugin, and if the output looks good to us, we can run `jest -u` to update the snapshot.

### AST Tests

In addition to snapshot testing, we can manually inspect the AST. This is a simple but brittle example. For more involved situations you may wish to leverage babel-traverse. It allows you to specify an object with a `visitor` key, exactly like you use for the plugin itself.

```js
it('contains baz', () => {
  const {ast} = babel.transform(example, {plugins: [plugin]});
  const program = ast.program;
  const declaration = program.body[0].declarations[0];
  assert.equal(declaration.id.name, 'baz');
  // or babelTraverse(program, {visitor: ...})
});
```

### Exec Tests

Here we'll be transforming the code, and then evaluating that it behaves correctly. Note that we're not using `assert` in the test. This ensures that if our plugin does weird stuff like removing the assert line by accident, the test will still fail.

```js
it('foo is an alias to baz', () => {
  var input = `
    var foo = 1;
    // test that foo was renamed to baz
    var res = baz;
  `;
  var {code} = babel.transform(input, {plugins: [plugin]});
  var f = new Function(`
    ${code};
    return res;
  `);
  var res = f();
  assert(res === 1, 'res is 1');
});
```

Babel core uses a [similar approach](https://github.com/babel/babel/blob/7.0/CONTRIBUTING.md#writing-tests) to snapshot and exec tests.

### [`babel-plugin-tester`](https://github.com/kentcdodds/babel-plugin-tester)

This package makes testing plugins easier. If you're familiar with ESLint's [RuleTester](http://eslint.org/docs/developer-guide/working-with-rules#rule-unit-tests) this should be familiar. You can look at [the docs](https://github.com/kentcdodds/babel-plugin-tester/blob/master/README.md) to get a full sense of what's possible, but here's a simple example:

```js
import pluginTester from 'babel-plugin-tester';
import identifierReversePlugin from '../identifier-reverse-plugin';

pluginTester({
  plugin: identifierReversePlugin,
  fixtures: path.join(__dirname, '__fixtures__'),
  tests: {
    'does not change code with no identifiers': '"hello";',
    'changes this code': {
      code: 'var hello = "hi";',
      output: 'var olleh = "hi";',
    },
    'using fixtures files': {
      fixture: 'changed.js',
      outputFixture: 'changed-output.js',
    },
    'using jest snapshots': {
      code: `
        function sayHi(person) {
          return 'Hello ' + person + '!'
        }
      `,
      snapshot: true,
    },
  },
});
```

* * *

> ***For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) and [@babeljs](https://twitter.com/babeljs) on Twitter.***

================================================
FILE: translations/ar/user-handbook.md
================================================
# Babel User Handbook

This document covers everything you ever wanted to know about using [Babel](https://babeljs.io) and related tooling.

[![cc-by-4.0](https://licensebuttons.net/l/by/4.0/80x15.png)](http://creativecommons.org/licenses/by/4.0/)

This handbook is available in other languages, see the [README](/README.md) for a complete list.

# Table of Contents

  * [Introduction](#toc-introduction)
  * [Setting up Babel](#toc-setting-up-babel) 
      * [`babel-cli`](#toc-babel-cli)
      * [Running Babel CLI from within a project](#toc-running-babel-cli-from-within-a-project)
      * [`babel-register`](#toc-babel-register)
      * [`babel-node`](#toc-babel-node)
      * [`babel-core`](#toc-babel-core)
  * [Configuring Babel](#toc-configuring-babel) 
      * [`.babelrc`](#toc-babelrc)
      * [`babel-preset-es2015`](#toc-babel-preset-es2015)
      * [`babel-preset-react`](#toc-babel-preset-react)
      * [`babel-preset-stage-x`](#toc-babel-preset-stage-x)
  * [Executing Babel-generated code](#toc-executing-babel-generated-code) 
      * [`babel-polyfill`](#toc-babel-polyfill)
      * [`babel-runtime`](#toc-babel-runtime)
  * [Configuring Babel (Advanced)](#toc-configuring-babel-advanced) 
      * [Manually specifying plugins](#toc-manually-specifying-plugins)
      * [Plugin options](#toc-plugin-options)
      * [Customizing Babel based on environment](#toc-customizing-babel-based-on-environment)
      * [Making your own preset](#toc-making-your-own-preset)
  * [Babel and other tools](#toc-babel-and-other-tools) 
      * [Static analysis tools](#toc-static-analysis-tools)
      * [Linting](#toc-linting)
      * [Code Style](#toc-code-style)
      * [Documentation](#toc-documentation)
      * [Frameworks](#toc-frameworks)
      * [React](#toc-react)
      * [Text Editors and IDEs](#toc-text-editors-and-ides)
  * [Babel Support](#toc-babel-support) 
      * [Babel Forum](#toc-babel-forum)
      * [Babel Chat](#toc-babel-chat)
      * [Babel Issues](#toc-babel-issues)
      * [Creating an awesome Babel bug report](#toc-creating-an-awesome-babel-bug-report)

# <a id="toc-introduction"></a>Introduction

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.

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.

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.

For example, Babel could transform the new ES2015 arrow function syntax from this:

```js
const square = n => n * n;
```

Into the following:

```js
const square = function square(n) {
  return n * n;
};
```

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.

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.

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

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.

> ***For future updates, follow [@thejameskyle](https://twitter.com/thejameskyle) on Twitter.***

* * *

# <a id="toc-setting-up-babel"></a>Setting up Babel

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.

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.

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

## <a id="toc-babel-cli"></a>`babel-cli`

Babel's CLI is a simple way to compile files with Babel from the command line.

Let's first install it globally to learn the basics.

```sh
$ npm install --global babel-cli
```

We can compile our first file like so:

```sh
$ babel my-file.js
```

This will dump the compiled output directly into your terminal. To write it to a file we'll specify an `--out-file` or `-o`.

```sh
$ babel example.js --out-file compiled.js
# or
$ babel example.js -o compiled.js
```

If we want to compile a whole directory into a new directory we can do so using `--out-dir` or `-d`.

```sh
$ babel src --out-dir lib
# or
$ babel src -d lib
```

### <a id="toc-running-babel-cli-from-within-a-project"></a>Running Babel CLI from within a project

While you *can* install Babel CLI globally on your machine, it's much better to install it **locally** project by project.

There are two primary reasons for this.

  1. Different projects on the same machine can depend on different versions of Babel allowing you to update one at a time.
  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.

We can install Babel CLI locally by running:

```sh
$ npm install --save-dev babel-cli
```

> **Note:** Since it's generally a bad idea to run Babel globally you may want to uninstall the global copy by running:
> 
> ```sh
$ npm uninstall --global babel-cli
```

After that finishes installing, your `package.json` file should look like this:

```json
{
  "name": "my-project",
  "version": "1.0.0",
  "devDependencies": {
    "babel-cli": "^6.0.0"
  }
}
```

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.

Simply add a `"scripts"` field to your `package.json` and put the babel command inside there as `build`.

```diff
  {
    "name": "my-project",
    "version": "1.0.0",
+   "scripts": {
+     "build": "babel src -d lib"
+   },
    "devDependencies": {
      "babel-cli": "^6.0.0"
    }
  }
```

Now from our terminal we can run:

```js
npm run build
```

This will run Babel the same way as before, only now we are using a local copy.

## <a id="toc-babel-register"></a>`babel-register`

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.

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.

First let's create an `index.js` file in our project.

```js
console.log("Hello world!");
```

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

First install `babel-register`.

```sh
$ npm install --save-dev babel-register
```

Next, create a `register.js` file in the project and write the following code:

```js
require("babel-register");
require("./index.js");
```

What this does is *registers* Babel in Node's module system and begins compiling every file that is `require`'d.

Now, instead of running `node index.js` we can use `register.js` instead.

```sh
$ node register.js
```

> **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.
> 
> ```js
require("babel-register");
// not compiled:
console.log("Hello world!");
```

## <a id="toc-babel-node"></a>`babel-node`

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.

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.

First make sure that you have `babel-cli` installed.

```sh
$ npm install --save-dev babel-cli
```

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

Then replace wherever you are running `node` with `babel-node`.

If you are using npm `scripts` you can simply do:

```diff
  {
    "scripts": {
-     "script-name": "node script.js"
+     "script-name": "babel-node script.js"
    }
  }
```

Otherwise you'll need to write out the path to `babel-node` itself.

```diff
- node script.js
+ ./node_modules/.bin/babel-node script.js
```

> Tip: You can also use [`npm-run`](https://www.npmjs.com/package/npm-run).

## <a id="toc-babel-core"></a>`babel-core`

If you need to use Babel programmatically for some reason, you can use the `babel-core` package itself.

First install `babel-core`.

```sh
$ npm install babel-core
```

```js
var babel = require("babel-core");
```

If you have a string of JavaScript you can compile it directly using `babel.transform`.

```js
babel.transform("code();", options);
// => { code, map, ast }
```

If you are working with files you can use either the asynchronous api:

```js
babel.transformFile("filename.js", options, function(err, result) {
  result; // => { code, map, ast }
});
```

Or the synchronous api:

```js
babel.transformFileSync("filename.js", options);
// => { code, map, ast }
```

If you already have a Babel AST for whatever reason you may transform from the AST directly.

```js
babel.transformFromAst(ast, code, options);
// => { code, map, ast }
```

For all of the above methods, `options` refers to https://babeljs.io/docs/usage/api/#options.

* * *

# <a id="toc-configuring-babel"></a>Configuring Babel

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.

This is because we haven't told Babel to do anything yet.

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

You can give Babel instructions on what to do by installing **plugins** or **presets** (groups of plugins).

## <a id="toc-babelrc"></a>`.babelrc`

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:

```js
{
  "presets": [],
  "plugins": []
}
```

This file is how you configure Babel to do what you want.

> **Note:** While you can also pass options to Babel in other ways the `.babelrc` file is convention and is the best way.

## <a id="toc-babel-preset-es2015"></a>`babel-preset-es2015`

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

We'll do this by installing the "es2015" Babel preset:

```sh
$ npm install --save-dev babel-preset-es2015
```

Next we'll modify our `.babelrc` to include that preset.

```diff
  {
    "presets": [
+     "es2015"
    ],
    "plugins": []
  }
```

## <a id="toc-babel-preset-react"></a>`babel-preset-react`

Setting up React is just as easy. Just install the preset:

```sh
$ npm install --save-dev babel-preset-react
```

Then add the preset to your `.babelrc` file:

```diff
  {
    "presets": [
      "es2015",
+     "react"
    ],
    "plugins": []
  }
```

## <a id="toc-babel-preset-stage-x"></a>`babel-preset-stage-x`

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.

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.

These are bundled in babel as 4 different presets:

  * `babel-preset-stage-0`
  * `babel-preset-stage-1`
  * `babel-preset-stage-2`
  * `babel-preset-stage-3`

> Note that there is no stage-4 preset as it is simply the `es2015` preset above.

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

Simply install the stage you are interested in using:

```sh
$ npm install --save-dev babel-preset-stage-2
```

Then you can add it to your `.babelrc` config.

```diff
  {
    "presets": [
      "es2015",
      "react",
+     "stage-2"
    ],
    "plugins": []
  }
```

* * *

# <a id="toc-executing-babel-generated-code"></a>Executing Babel-generated code

So you've compiled your code with Babel, but this is not the end of the story.

## <a id="toc-babel-polyfill"></a>`babel-polyfill`

Almost all futuristic JavaScript syntax can be compiled with Babel, but the same is not true for APIs.

For example, the following code has an arrow function that needs to be compiled:

```js
function addAll() {
  return Array.from(arguments).reduce((a, b) => a + b);
}
```

Which turns into this:

```js
function addAll() {
  return Array.from(arguments).reduce(function(a, b) {
    return a + b;
  });
}
```

However, this still won't work everywhere because `Array.from` doesn't exist in every JavaScript environment.

    Uncaught TypeError: Array.from is not a function
    

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.

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.

To include the Babel polyfill, first install it with npm:

```sh
$ npm install --save babel-polyfill
```

Then simply include the polyfill at the top of any file that requires it:

```js
import "babel-polyfill";
```

## <a id="toc-babel-runtime"></a>`babel-runtime`

In order to implement details of ECMAScript specs, Babel will use "helper" methods in order to keep the generated code clean.

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.

Start by installing `babel-plugin-transform-runtime` and `babel-runtime`:

```sh
$ npm install --save-dev babel-plugin-transform-runtime
$ npm install --save babel-runtime
```

Then update your `.babelrc`:

```diff
  {
    "plugins": [
+     "transform-runtime",
      "transform-es2015-classes"
    ]
  }
```

Now Babel will compile code like the following:

```js
class Foo {
  method() {}
}
```

Into this:

```js
import _classCallCheck from "babel-runtime/helpers/classCallCheck";
import _createClass from "babel-runtime/helpers/createClass";

let Foo = function () {
  function Foo() {
    _classCallCheck(this, Foo);
  }

  _createClass(Foo, [{
    key: "method",
    value: function method() {}
  }]);

  return Foo;
}();
```

Rather than putting the `_classCallCheck` and `_createClass` helpers in every single file where they are needed.

* * *

# <a id="toc-configuring-babel-advanced"></a>Configuring Babel (Advanced)

Most people can get by using Babel with just the built-in presets, but Babel exposes much finer-grained power than that.

## <a id="toc-manually-specifying-plugins"></a>Manually specifying plugins

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.

First install a plugin:

```sh
$ npm install --save-dev babel-plugin-transform-es2015-classes
```

Then add the `plugins` field to your `.babelrc`.

```diff
  {
+   "plugins": [
+     "transform-es2015-classes"
+   ]
  }
```

This gives you much finer grained control over the exact transforms you are running.

For a full list of official plugins see the [Babel Plugins page](http://babeljs.io/docs/plugins/).

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

## <a id="toc-plugin-options"></a>Plugin options

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.

To add options to a plugin, simply make the following change:

```diff
  {
    "plugins": [
-     "transform-es2015-classes"
+     ["transform-es2015-classes", { "loose": true }]
    ]
  }
```

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

## <a id="toc-customizing-babel-based-on-environment"></a>Customizing Babel based on environment

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.

For this reason, it is common to want Babel configuration based on the environment. You can do this easily with your `.babelrc` file.

```diff
  {
    "presets": ["es2015"],
    "plugins": [],
+   "env": {
+     "development": {
+       "plugins": [...]
+     },
+     "production": {
+       "plugins": [...]
+     }
    }
  }
```

Babel will enable configuration inside of `env` based on the current environment.

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

**Unix**

```sh
$ BABEL_ENV=production [COMMAND]
$ NODE_ENV=production [COMMAND]
```

**Windows**

```sh
$ SET BABEL_ENV=production
$ [COMMAND]
```

> **Note:** `[COMMAND]` is whatever you use to run Babel (ie. `babel`, `babel-node`, or maybe just `node` if you are using the register hook).
> 
> **Tip:** If you want your command to work across unix and windows platforms then use [`cross-env`](https://www.npmjs.com/package/cross-env).

## <a id="toc-making-your-own-preset"></a>Making your own preset

Manually specifying plugins? Plugin options? Environment-based settings? All this configuration might seem like a ton of repetition for all of your projects.

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

It's easy to create a preset. Say you have this `.babelrc` file:

```js
{
  "presets": [
    "es2015",
    "react"
  ],
  "plugins": [
    "transform-flow-strip-types"
  ]
}
```

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.

First, create a new `package.json` file with the necessary `dependencies` for your preset.

```js
{
  "name": "babel-preset-my-awesome-preset",
  "version": "1.0.0",
  "author": "James Kyle <me@thejameskyle.com>",
  "dependencies": {
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.3.13",
    "babel-plugin-transform-flow-strip-types": "^6.3.15"
  }
}
```

Then create an `index.js` file that exports the contents of your `.babelrc` file, replacing plugin/preset strings with `require` calls.

```js
module.exports = {
  presets: [
    require("babel-preset-es2015"),
    require("babel-preset-react")
  ],
  plugins: [
    require("babel-plugin-transform-flow-strip-types")
  ]
};
```

Then simply publish this to npm and you can use it like you would any preset.

* * *

# <a id="toc-babel-and-other-tools"></a>Babel and other tools

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.

## <a id="toc-static-analysis-tools"></a>Static analysis tools

Newer standards bring a lot of new syntax to the language and static analysis tools are just starting to take advantage of it.

### <a id="toc-linting"></a>Linting

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.

First install `eslint` and `babel-eslint`.

```sh
$ npm install --save-dev eslint babel-eslint
```

Next create or use the existing `.eslintrc` file in your project and set the `parser` as `babel-eslint`.

```diff
  {
+   "parser": "babel-eslint",
    "rules": {
      ...
    }
  }
```

Now add a `lint` task to your npm `package.json` scripts:

```diff
  {
    "name": "my-module",
    "scripts": {
+     "lint": "eslint my-files.js"
    },
    "devDependencies": {
      "babel-eslint": "...",
      "eslint": "..."
    }
  }
```

Then just run the task and you will be all setup.

```sh
$ npm run lint
```

For more information consult the [`babel-eslint`](https://github.com/babel/babel-eslint) or [`eslint`](http://eslint.org) documentation.

### <a id="toc-code-style"></a>Code Style

> JSCS has merged with ESLint, so checkout Code Styling with ESLint.

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.

Even better, this integration now lives within JSCS itself under the `--esnext` option. So integrating Babel is as easy as:

    $ jscs . --esnext
    

From the cli, or adding the `esnext` option to your `.jscsrc` file.

```diff
  {
    "preset": "airbnb",
+   "esnext": true
  }
```

For more information consult the [`babel-jscs`](https://github.com/jscs-dev/babel-jscs) or [`jscs`](http://jscs.info) documentation.

<!--
### Code Coverage

> [WIP]
-->

### <a id="toc-documentation"></a>Documentation

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.

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.

## <a id="toc-frameworks"></a>Frameworks

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.

Frameworks have the opportunity not just to use Babel but to extend it in ways that improve their users' experience.

### <a id="toc-react"></a>React

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

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

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.

<!--
### Ember

> [WIP]
-->

## <a id="toc-text-editors-and-ides"></a>Text Editors and IDEs

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.

  * [Sublime Text](https://github.com/babel/babel-sublime)
  * [Atom](https://atom.io/packages/language-babel)
  * [Vim](https://github.com/jbgutierrez/vim-babel)
  * [WebStorm](https://babeljs.io/docs/setup/#webstorm)

<!--
# Debugging Babel

> [WIP]
-->

* * *

# <a id="toc-babel-support"></a>Babel Support

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.

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.

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.

## <a id="toc-babel-forum"></a>Babel Forum

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

## <a id="toc-babel-chat"></a>Babel Chat

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

<!--
## Babel Stack Overflow

> [WIP]
-->

## <a id="toc-babel-issues"></a>Babel Issues

Babel uses the issue tracker provided by [Github](http://github.com).

You can see all the open and closed issues on [Github](https://github.com/babel/babel/issues).

If you want to open a new issue:

  * [Search for an existing issue](https://github.com/babel/babel/issues)
  * [Create a new bug report](https://github.com/babel/babel/issues/new) or [request a new feature](https://github.com/babel/babel/issues/new)

### <a id="toc-creating-an-awesome-babel-bug-report"></a>Creating an awesome Babel bug report

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.

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.

> [WIP]

* * *

> ***For future updates, follow [@thejameskyle](https://twitter.com/the
Download .txt
gitextract__u4zmoof/

├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── crowdin.yaml
├── package.json
└── translations/
    ├── af/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── ar/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── ca/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── cs/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── da/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── de/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── el/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── en/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── es-ES/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── fa-IR/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── fi/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── fr/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── he/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── hu/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── id-ID/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── it/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── ja/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── ko/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── nl/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── no/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── pl/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── pt-BR/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── pt-PT/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── ro/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── ru/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── sk-SK/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── sr/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── sv-SE/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── tr/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── uk/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── vi/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    ├── zh-Hans/
    │   ├── README.md
    │   ├── plugin-handbook.md
    │   └── user-handbook.md
    └── zh-Hant/
        ├── README.md
        ├── plugin-handbook.md
        └── user-handbook.md
Condensed preview — 105 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (3,004K chars).
[
  {
    "path": ".gitignore",
    "chars": 19,
    "preview": "node_modules\n*.log\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 1823,
    "preview": "# Contributing\n\n### Translating the handbook\n\nThe English translation of this handbook is maintained in this repository,"
  },
  {
    "path": "LICENSE",
    "chars": 18542,
    "preview": "Creative Commons Attribution 4.0 International\n\n=======================================================================\n"
  },
  {
    "path": "README.md",
    "chars": 4136,
    "preview": "# Babel Handbook\n\nWritten by [Jamie Kyle](https://jamie.build/)\n\nA guided handbook on how to use Babel and how to create"
  },
  {
    "path": "crowdin.yaml",
    "chars": 824,
    "preview": "project_identifier: babel-plugin-handbook\napi_key_env: CROWDIN_API_KEY\nbase_path: .\nfiles:\n  - source: '/translations/en"
  },
  {
    "path": "package.json",
    "chars": 372,
    "preview": "{\n  \"name\": \"babel-handbook\",\n  \"version\": \"1.0.0\",\n  \"description\": \"How to Babel\",\n  \"repository\": \"thejameskyle/babel"
  },
  {
    "path": "translations/af/README.md",
    "chars": 948,
    "preview": "# Babel Handbook\n\nThis handbook is divided into two parts:\n\n  * [User Handbook](user-handbook.md) - How to setup/configu"
  },
  {
    "path": "translations/af/plugin-handbook.md",
    "chars": 57565,
    "preview": "# Babel Plugin Handbook\n\nThis document covers how to create [Babel](https://babeljs.io) [plugins](https://babeljs.io/doc"
  },
  {
    "path": "translations/af/user-handbook.md",
    "chars": 27881,
    "preview": "# Babel User Handbook\n\nThis document covers everything you ever wanted to know about using [Babel](https://babeljs.io) a"
  },
  {
    "path": "translations/ar/README.md",
    "chars": 948,
    "preview": "# Babel Handbook\n\nThis handbook is divided into two parts:\n\n  * [User Handbook](user-handbook.md) - How to setup/configu"
  },
  {
    "path": "translations/ar/plugin-handbook.md",
    "chars": 57557,
    "preview": "# Babel Plugin Handbook\n\nThis document covers how to create [Babel](https://babeljs.io) [plugins](https://babeljs.io/doc"
  },
  {
    "path": "translations/ar/user-handbook.md",
    "chars": 27881,
    "preview": "# Babel User Handbook\n\nThis document covers everything you ever wanted to know about using [Babel](https://babeljs.io) a"
  },
  {
    "path": "translations/ca/README.md",
    "chars": 998,
    "preview": "# Manual de Babel\n\nAquest manual està dividit en dues parts:\n\n  * [Manual d'usuari](user-handbook.md) - Com configurar B"
  },
  {
    "path": "translations/ca/plugin-handbook.md",
    "chars": 57631,
    "preview": "# Babel Plugin Handbook\n\nThis document covers how to create [Babel](https://babeljs.io) [plugins](https://babeljs.io/doc"
  },
  {
    "path": "translations/ca/user-handbook.md",
    "chars": 28035,
    "preview": "# Manual d'usuari de Babel\n\nAquest document abasta tot el que sempre ha volgut saber sobre com utilitzar [Babel](https:/"
  },
  {
    "path": "translations/cs/README.md",
    "chars": 915,
    "preview": "# Babel příručka\n\nTato příručka je rozdělena do dvou částí:\n\n  * [Uživatelská příručka](user-handbook.md) - Jak nainstal"
  },
  {
    "path": "translations/cs/plugin-handbook.md",
    "chars": 57498,
    "preview": "# Příručka pro pluginy Babelu\n\nTento dokument popisuje, jak vytvořit [Babel](https://babeljs.io) [pluginy](https://babel"
  },
  {
    "path": "translations/cs/user-handbook.md",
    "chars": 27854,
    "preview": "# Babel User Handbook\n\nThis document covers everything you ever wanted to know about using [Babel](https://babeljs.io) a"
  },
  {
    "path": "translations/da/README.md",
    "chars": 948,
    "preview": "# Babel Handbook\n\nThis handbook is divided into two parts:\n\n  * [User Handbook](user-handbook.md) - How to setup/configu"
  },
  {
    "path": "translations/da/plugin-handbook.md",
    "chars": 57565,
    "preview": "# Babel Plugin Handbook\n\nThis document covers how to create [Babel](https://babeljs.io) [plugins](https://babeljs.io/doc"
  },
  {
    "path": "translations/da/user-handbook.md",
    "chars": 27881,
    "preview": "# Babel User Handbook\n\nThis document covers everything you ever wanted to know about using [Babel](https://babeljs.io) a"
  },
  {
    "path": "translations/de/README.md",
    "chars": 939,
    "preview": "# Babel Handbuch\n\nDas Handbuch besteht aus zwei Teilen:\n\n  * [Nutzerhandbuch](user-handbook.md) - Babel aufsetzen, konfi"
  },
  {
    "path": "translations/de/plugin-handbook.md",
    "chars": 58086,
    "preview": "# Babel Plugin Handbook\n\nDieses Dokument beschreibt das Erstellen von [Babel](https://babeljs.io) [Plugins](https://babe"
  },
  {
    "path": "translations/de/user-handbook.md",
    "chars": 27895,
    "preview": "# Babel User Handbook\n\nThis document covers everything you ever wanted to know about using [Babel](https://babeljs.io) a"
  },
  {
    "path": "translations/el/README.md",
    "chars": 1093,
    "preview": "# Εγχειρίδιο Babel\n\nΑυτό το εγχειρίδιο χωρίζεται σε δύο μέρη:\n\n  * [Εγχειρίδιο Χρήστη](user-handbook.md) - Πως να ρυθμίσ"
  },
  {
    "path": "translations/el/plugin-handbook.md",
    "chars": 59055,
    "preview": "# Babel: Εγχειρίδιο για νέους χρήστες\n\nΤο παρόν έγγραφο καλύπτει πώς να δημιουργήσετε [Babel](https://babeljs.io) [plugi"
  },
  {
    "path": "translations/el/user-handbook.md",
    "chars": 31202,
    "preview": "# Εγχειρίδιο Χρήσης Babel\n\nΑυτό το κέιμενο καλύπτει οτι θα ήθελε να μάθει κάποιος σχετικά με την χρήση του [Babel](https"
  },
  {
    "path": "translations/en/README.md",
    "chars": 853,
    "preview": "# Babel Handbook\n\nThis handbook is divided into two parts:\n\n- [User Handbook](user-handbook.md) - How to setup/configure"
  },
  {
    "path": "translations/en/plugin-handbook.md",
    "chars": 58023,
    "preview": "# Babel Plugin Handbook\n\nWritten by [Jamie Kyle](https://jamie.build/)\n\nThis document covers how to create [Babel](https"
  },
  {
    "path": "translations/en/user-handbook.md",
    "chars": 27647,
    "preview": "# Babel User Handbook\n\nWritten by [Jamie Kyle](https://jamie.build/)\n\nThis document covers everything you ever wanted to"
  },
  {
    "path": "translations/es-ES/README.md",
    "chars": 1000,
    "preview": "# Manual de Babel\n\nEste manual está dividido en dos partes:\n\n  * [Manual de usuario](user-handbook.md) - Cómo configurar"
  },
  {
    "path": "translations/es-ES/plugin-handbook.md",
    "chars": 58791,
    "preview": "# Manual para Plugins Babel\n\nEste documento abarca cómo crear [plugins](https://babeljs.io/docs/advanced/plugins/) para "
  },
  {
    "path": "translations/es-ES/user-handbook.md",
    "chars": 30037,
    "preview": "# Manual de usuario de Babel\n\nEste documento abarca todo lo que siempre quizo saber sobre como usar [Babel](https://babe"
  },
  {
    "path": "translations/fa-IR/README.md",
    "chars": 964,
    "preview": "# کتاب راهنمای Babel\n\nاین کتاب راهنما به دو بخش تقسیم شده است:\n\n  * [راهنمای کاربر](user-handbook.md) - نحوه ی آماده ساز"
  },
  {
    "path": "translations/fa-IR/plugin-handbook.md",
    "chars": 57575,
    "preview": "# Babel Plugin Handbook\n\nThis document covers how to create [Babel](https://babeljs.io) [plugins](https://babeljs.io/doc"
  },
  {
    "path": "translations/fa-IR/user-handbook.md",
    "chars": 28067,
    "preview": "# کتاب راهنمای کاربر Babel\n\nدر این نوشتار شما با تمام مفاهیم [Babel](https://babeljs.io) و همچنین ابزرهای مربوط به آن، م"
  },
  {
    "path": "translations/fi/README.md",
    "chars": 924,
    "preview": "# Babel -käsikirja\n\nKäsikirja koostuu kahdesta osasta:\n\n  * [Käyttäjän käsikirja](user-handbook.md) - Babel asennus/konf"
  },
  {
    "path": "translations/fi/plugin-handbook.md",
    "chars": 57907,
    "preview": "# Babel Plugin Handbook\n\nTässä ohjeessa käsitellään [Babel](https://babeljs.io) [lisäosien](https://babeljs.io/docs/adva"
  },
  {
    "path": "translations/fi/user-handbook.md",
    "chars": 27848,
    "preview": "# Babel User Handbook\n\nThis document covers everything you ever wanted to know about using [Babel](https://babeljs.io) a"
  },
  {
    "path": "translations/fr/README.md",
    "chars": 984,
    "preview": "# Manuel de Babel\n\nCe manuel est divisé en deux parties :\n\n  * [Manuel utilisateur](user-handbook.md) - Comment démarrer"
  },
  {
    "path": "translations/fr/plugin-handbook.md",
    "chars": 62471,
    "preview": "# Manuel du plugin de Babel\n\nCe présent document décrit les méthodes de création des [plugins](https://babeljs.io/docs/a"
  },
  {
    "path": "translations/fr/user-handbook.md",
    "chars": 31443,
    "preview": "# Manuel utilisateur de Babel\n\nCe document couvre tout ce que vous avez toujours voulu savoir sur l'utilisation de [Babe"
  },
  {
    "path": "translations/he/README.md",
    "chars": 856,
    "preview": "# Babel Handbook\n\nThis handbook is divided into two parts:\n\n  * [User Handbook](user-handbook.md) - How to setup/configu"
  },
  {
    "path": "translations/he/plugin-handbook.md",
    "chars": 57633,
    "preview": "# Babel Plugin Handbook\n\nבמסמך הזה נלמד כיצד ליצור [הרחבות](https://babeljs.io/docs/advanced/plugins/) ל-[Babel](https:/"
  },
  {
    "path": "translations/he/user-handbook.md",
    "chars": 27861,
    "preview": "# Babel User Handbook\n\nThis document covers everything you ever wanted to know about using [Babel](https://babeljs.io) a"
  },
  {
    "path": "translations/hu/README.md",
    "chars": 948,
    "preview": "# Babel Handbook\n\nThis handbook is divided into two parts:\n\n  * [User Handbook](user-handbook.md) - How to setup/configu"
  },
  {
    "path": "translations/hu/plugin-handbook.md",
    "chars": 57565,
    "preview": "# Babel Plugin Handbook\n\nThis document covers how to create [Babel](https://babeljs.io) [plugins](https://babeljs.io/doc"
  },
  {
    "path": "translations/hu/user-handbook.md",
    "chars": 27881,
    "preview": "# Babel User Handbook\n\nThis document covers everything you ever wanted to know about using [Babel](https://babeljs.io) a"
  },
  {
    "path": "translations/id-ID/README.md",
    "chars": 1009,
    "preview": "# Paduan Babel\n\nBuku ini dibagi menjadi dua bagian:\n\n  * [Pengguna Handbook](user-handbook.md) - bagaimana setup/konfigu"
  },
  {
    "path": "translations/id-ID/plugin-handbook.md",
    "chars": 58124,
    "preview": "# Pedoman Plungin Babel\n\nDokumen ini berisi langkah pembuatan [Babel](https://babeljs.io) [plugin](https://babeljs.io/do"
  },
  {
    "path": "translations/id-ID/user-handbook.md",
    "chars": 29998,
    "preview": "# Paduan Pengguna Babel\n\nDokumen ini mencakup semua yang ingin Anda tahu tentang menggunakan [Babel](https://babeljs.io)"
  },
  {
    "path": "translations/it/README.md",
    "chars": 1025,
    "preview": "# Manuale di Babel\n\nQuesto manuale è diviso in due parti:\n\n  * [Manuale dell'utente](user-handbook.md) - Installazione/c"
  },
  {
    "path": "translations/it/plugin-handbook.md",
    "chars": 59051,
    "preview": "# Babel Plugin Handbook\n\nQuesto documento include le linee guida per la creazione di [plugins](https://babeljs.io/docs/a"
  },
  {
    "path": "translations/it/user-handbook.md",
    "chars": 27921,
    "preview": "# Manuale utente di Babel\n\nThis document covers everything you ever wanted to know about using [Babel](https://babeljs.i"
  },
  {
    "path": "translations/ja/README.md",
    "chars": 515,
    "preview": "# Babel Handbook\n\nこのハンドブックは2つの資料に分かれています。\n\n  * [User Handbook](user-handbook.md) - Babel等のセットアップと設定について\n  * [Plugin Hand"
  },
  {
    "path": "translations/ja/plugin-handbook.md",
    "chars": 55732,
    "preview": "# Babel Plugin Handbook\n\nこのドキュメントでは[Babel](https://babeljs.io)の[プラグイン](https://babeljs.io/docs/advanced/plugins/)を作る方法を解"
  },
  {
    "path": "translations/ja/user-handbook.md",
    "chars": 26364,
    "preview": "# Babel User Handbook\n\nこのドキュメントはあなたが知りたい[Babel](https://babeljs.io)やその関連ツールの使い方をカバーします。\n\n[![cc-by-4.0](https://licensebu"
  },
  {
    "path": "translations/ko/README.md",
    "chars": 609,
    "preview": "# Babel Handbook\n\n이 핸드북은 두 파트로 분리되어 있습니다:\n\n  * [User Handbook](user-handbook.md) - Babel을 설치/운용 하는 방법과 여러가지\n  * [Plugin "
  },
  {
    "path": "translations/ko/plugin-handbook.md",
    "chars": 52114,
    "preview": "# Babel Plugin Handbook\n\n이 문서는 [Babel](https://babeljs.io) [플러그인](https://babeljs.io/docs/advanced/plugins/)을 만드는 방법을 설명"
  },
  {
    "path": "translations/ko/user-handbook.md",
    "chars": 20755,
    "preview": "# Babel User Handbook\n\n이 문서는 모든 [Babel](https://babeljs.io)과 관련된 도구를 사용하는 방법에 대해 설명합니다.\n\n[![cc-by-4.0](https://licensebu"
  },
  {
    "path": "translations/nl/README.md",
    "chars": 928,
    "preview": "# Babel handboek\n\nDit handboek is onderverdeeld in twee delen:\n\n  * [Gebruikershandleiding](user-handbook.md) - hoe Babe"
  },
  {
    "path": "translations/nl/plugin-handbook.md",
    "chars": 57654,
    "preview": "# Babel Plugin Handleiding\n\nDit document beschrijft hoe [Babel](https://babeljs.io) [plugins](https://babeljs.io/docs/ad"
  },
  {
    "path": "translations/nl/user-handbook.md",
    "chars": 28086,
    "preview": "# Babel Gebruikershandleiding\n\nDit document bevat alles wat je ooit zou willen weten over het gebruik van [Babel](https:"
  },
  {
    "path": "translations/no/README.md",
    "chars": 948,
    "preview": "# Babel Handbook\n\nThis handbook is divided into two parts:\n\n  * [User Handbook](user-handbook.md) - How to setup/configu"
  },
  {
    "path": "translations/no/plugin-handbook.md",
    "chars": 57765,
    "preview": "# Babel Plugin Handbook\n\nThis document covers how to create [Babel](https://babeljs.io) [plugins](https://babeljs.io/doc"
  },
  {
    "path": "translations/no/user-handbook.md",
    "chars": 27881,
    "preview": "# Babel User Handbook\n\nThis document covers everything you ever wanted to know about using [Babel](https://babeljs.io) a"
  },
  {
    "path": "translations/pl/README.md",
    "chars": 982,
    "preview": "# Babel Podręcznik\n\nTen podręcznik jest podzielony na dwie części:\n\n  * [Podręcznik Użytkownika](user-handbook.md) - Jak"
  },
  {
    "path": "translations/pl/plugin-handbook.md",
    "chars": 57570,
    "preview": "# Babel Plugin Podręcznik\n\nThis document covers how to create [Babel](https://babeljs.io) [plugins](https://babeljs.io/d"
  },
  {
    "path": "translations/pl/user-handbook.md",
    "chars": 28600,
    "preview": "# Podręcznik Użytkownika Babel\n\nTen dokument obejmuje wszystko, co chciałbyś wiedzieć o [Babelu](https://babeljs.io) i p"
  },
  {
    "path": "translations/pt-BR/README.md",
    "chars": 949,
    "preview": "# Babel Handbook\n\nEste manual está dividido em duas partes:\n\n  * [Manual do usuário](user-handbook.md) - como configurar"
  },
  {
    "path": "translations/pt-BR/plugin-handbook.md",
    "chars": 58504,
    "preview": "# Babel Plugin Handbook\n\nEste documento aborda como criar [plugins](https://babeljs.io/docs/advanced/plugins/) para o [B"
  },
  {
    "path": "translations/pt-BR/user-handbook.md",
    "chars": 30038,
    "preview": "# Manual do Usuário do Babel\n\nEste documento abrange tudo o que você sempre quis saber sobre a utilização do [Babel](htt"
  },
  {
    "path": "translations/pt-PT/README.md",
    "chars": 1002,
    "preview": "# Manual de Babel\n\nEste manual está dividido em duas partes:\n\n  * [Manual do utilizador](user-handbook.md) - Como config"
  },
  {
    "path": "translations/pt-PT/plugin-handbook.md",
    "chars": 57674,
    "preview": "# Manual de Plugins de Babel\n\nEste documento explica como criar [plugins](https://babeljs.io/docs/advanced/plugins/) par"
  },
  {
    "path": "translations/pt-PT/user-handbook.md",
    "chars": 27964,
    "preview": "# Manual do utilizador de Babel\n\nEste documento abrange tudo o que sempre quis saber sobre o uso de [Babel](https://babe"
  },
  {
    "path": "translations/ro/README.md",
    "chars": 984,
    "preview": "# Manualul Babel\n\nAcest manual este împărţit în două părţi:\n\n  * [Manualul utilizatorului](user-handbook.md) - modul de "
  },
  {
    "path": "translations/ro/plugin-handbook.md",
    "chars": 60890,
    "preview": "# Manualul pentru Plugin-uri Babel\n\nAcest document descrie cum se pot crea [plugin-uri](https://babeljs.io/docs/advanced"
  },
  {
    "path": "translations/ro/user-handbook.md",
    "chars": 29571,
    "preview": "# Manualul de utilizare Babel\n\nAcest document conține tot ceea ce ați vrut vreodată să ştiți despre utilizarea [Babel](h"
  },
  {
    "path": "translations/ru/README.md",
    "chars": 948,
    "preview": "# Справочник Babel\n\nЭто руководство разделено на две части:\n\n  * [Руководство Пользователя](user-handbook.md) - Установк"
  },
  {
    "path": "translations/ru/plugin-handbook.md",
    "chars": 58424,
    "preview": "# Руководство Плагинов Babel\n\nВ этом документе описано как создавать [плагины](https://babeljs.io/docs/advanced/plugins/"
  },
  {
    "path": "translations/ru/user-handbook.md",
    "chars": 28704,
    "preview": "# Babel. Руководство Пользователя\n\nЭтот документ охватывает все, что Вы когда-либо хотели знать об использовании [Babel]"
  },
  {
    "path": "translations/sk-SK/README.md",
    "chars": 919,
    "preview": "# Babel príručka\n\nPríručka je rozdelená do dvoch častí:\n\n  * [Užívateľská príručka](user-handbook.md) - Ako nainštalovať"
  },
  {
    "path": "translations/sk-SK/plugin-handbook.md",
    "chars": 57783,
    "preview": "# Príručka Babel pluginov\n\nTento dokument popisuje, ako vytvoriť [Babel](https://babeljs.io) [pluginy](https://babeljs.i"
  },
  {
    "path": "translations/sk-SK/user-handbook.md",
    "chars": 27848,
    "preview": "# Babel užívateľská príručka\n\nThis document covers everything you ever wanted to know about using [Babel](https://babelj"
  },
  {
    "path": "translations/sr/README.md",
    "chars": 967,
    "preview": "# Вавилон Приручник\n\nОвај приручник је подељен у два дела:\n\n  * [Кориснички Приручник](user-handbook.md) - Како да подес"
  },
  {
    "path": "translations/sr/plugin-handbook.md",
    "chars": 59167,
    "preview": "# Babel Plugin Handbook\n\nU dokumentu je objašnjeno kako se kreiraju [Babel](https://babeljs.io) [plaginovi](https://babe"
  },
  {
    "path": "translations/sr/user-handbook.md",
    "chars": 28093,
    "preview": "# Вавилон Кориснички Приручник\n\nОвај документ покрива све што сте увек желели да знате о коришћењу [Вавилона](https://ba"
  },
  {
    "path": "translations/sv-SE/README.md",
    "chars": 911,
    "preview": "# Babelhandbok\n\nDenna handbok är indelad i två delar:\n\n  * [Användarhandbok](user-handbook.md) - installation/konfigurer"
  },
  {
    "path": "translations/sv-SE/plugin-handbook.md",
    "chars": 57509,
    "preview": "# Babel Plugin handbok\n\nDet här dokumentet tar upp hur man skapar [Babel](https://babeljs.io) [plugins](https://babeljs."
  },
  {
    "path": "translations/sv-SE/user-handbook.md",
    "chars": 27953,
    "preview": "# Babel användarhandbok\n\nDet här dokumentet tar upp allt du någonsin skulle vilja veta om hur du använder [Babel](https:"
  },
  {
    "path": "translations/tr/README.md",
    "chars": 928,
    "preview": "# Babel El Kitabı\n\nBu el kitabı iki bölümden oluşur:\n\n  * [Kullanıcı el kitabı](user-handbook.md) - Kurulum yapılandırıl"
  },
  {
    "path": "translations/tr/plugin-handbook.md",
    "chars": 57454,
    "preview": "# Babel Handbook eklentisi\n\nBu belge [Babel ](https://babeljs.io) [eklentisinin](https://babeljs.io/docs/advanced/plugin"
  },
  {
    "path": "translations/tr/user-handbook.md",
    "chars": 28970,
    "preview": "# Babel Kullanıcı Elkitabı\n\nBu belge [Babel](https://babeljs.io) ve ilgili araçları ile ilgili bilmek isteyeceğiniz herş"
  },
  {
    "path": "translations/uk/README.md",
    "chars": 996,
    "preview": "# Довідник Babel\n\nЦей довідник складається з двох частин:\n\n  * [Довідник користувача](user-handbook.md) - Як встановити/"
  },
  {
    "path": "translations/uk/plugin-handbook.md",
    "chars": 57664,
    "preview": "# Довідник розробника плагінів до Babel\n\nЦей документ містить інформацію про те, як створювати плагіни ([plugins](https:"
  },
  {
    "path": "translations/uk/user-handbook.md",
    "chars": 30022,
    "preview": "# Довідник користувача Babel\n\nЦей документ містить всю необхідну інформацію стосовно використання [Babel](https://babelj"
  },
  {
    "path": "translations/vi/README.md",
    "chars": 948,
    "preview": "# Babel Handbook\n\nThis handbook is divided into two parts:\n\n  * [User Handbook](user-handbook.md) - How to setup/configu"
  },
  {
    "path": "translations/vi/plugin-handbook.md",
    "chars": 57703,
    "preview": "# Babel Plugin Handbook\n\nTài liệu này hướng dẫn làm cách nào để tạo ra [Babel](https://babeljs.io) [plugins](https://bab"
  },
  {
    "path": "translations/vi/user-handbook.md",
    "chars": 27869,
    "preview": "# Babel User Handbook\n\nThis document covers everything you ever wanted to know about using [Babel](https://babeljs.io) a"
  },
  {
    "path": "translations/zh-Hans/README.md",
    "chars": 400,
    "preview": "# Babel 手册\n\n这本手册分为两个部分:\n\n  * [用户手册](user-handbook.md)-如何安装/配置 Babel 及相关内容。\n  * [插件手册](plugin-handbook.md)-如何为 Babel 创建插件"
  },
  {
    "path": "translations/zh-Hans/plugin-handbook.md",
    "chars": 44452,
    "preview": "# Babel 插件手册\n\n这篇文档涵盖了如何创建 [Babel](https://babeljs.io) [插件](https://babeljs.io/docs/advanced/plugins/)等方面的内容。.\n\n[![cc-by-"
  },
  {
    "path": "translations/zh-Hans/user-handbook.md",
    "chars": 17712,
    "preview": "# Babel 用户手册\n\n这本手册涵盖了关于 [Babel](https://babeljs.io) 的使用及其相关工具的内容。\n\n[![cc-by-4.0](https://licensebuttons.net/l/by/4.0/80x"
  },
  {
    "path": "translations/zh-Hant/README.md",
    "chars": 430,
    "preview": "# Babel 使用手冊\n\n本手冊分為兩部分:\n\n  * [使用者手冊](user-handbook.md) - 如何安裝與配置 Babel\n  * [外掛手冊](plugin-handbook.md) - 如何撰寫 Babel 的外掛程式"
  },
  {
    "path": "translations/zh-Hant/plugin-handbook.md",
    "chars": 56610,
    "preview": "# Babel 外掛手冊\n\n這份文件提共如何使用 [Babel](https://babeljs.io)[外掛](https://babeljs.io/docs/advanced/plugins/).\n\n[![cc-by-4.0](http"
  },
  {
    "path": "translations/zh-Hant/user-handbook.md",
    "chars": 23022,
    "preview": "# Babel 使用手冊\n\n本文件包含了[Babel](https://babeljs.io)及其相關工具的所有資訊。\n\n[![cc-by-4.0](https://licensebuttons.net/l/by/4.0/80x15.png"
  }
]

About this extraction

This page contains the full source code of the jamiebuilds/babel-handbook GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 105 files (2.7 MB), approximately 722.2k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!