Next: , Previous: , Up: Babel   [Index]


3.4.3 Plugins and Presets

Transformations come in the form of plugins, which are small JavaScript programs that instruct Babel on how to carry out transformations to the code.

To transform ‘ES2015+’ syntax into ‘ES5’ we can rely on official plugins like @babel/plugin-transform-arrow-functions:

npm install --save-dev @babel/plugin-transform-arrow-functions
./node_modules/.bin/babel src --out-dir lib \
     --plugins=@babel/plugin-transform-arrow-functions

Now any arrow functions in our code will be transformed into ES5 compatible function expressions.

But we also have other ‘ES2015+’ features in our code that we want transformed. Instead of adding all the plugins we want one by one, we can use a "preset" which is just a pre-determined set of plugins.

For our use case here, there’s an excellent preset named ‘env’.

npm install --save-dev @babel/preset-env
./node_modules/.bin/babel src --out-dir lib \
     --presets=@babel/env

Without any configuration, this preset will include all plugins to support modern JavaScript (‘ES2015’, ‘ES2016’, etc.). But presets can take options too. Rather than passing both ‘cli’ and ‘preset’ options from the terminal, let’s look at another way of passing options: configuration files.

Create a file called babel.config.json (requires v7.8.0 and above) with the following content:

{
"presets": [
  [
  "@babel/env",
    {
      "targets": {
        "edge": "17",
        "firefox": "60",
        "chrome": "67",
        "safari": "11.1"
        }
      }
    ]
  ]
}

Now the ‘env’ preset will only load transformation plugins for features that are not available in our target browsers. We’re all set for syntax.