Difference between plugins and presets in .babelrc

2019-06-17 01:20发布

问题:

Situation

So I have a .babelrc like this:

{
    "presets": [
        "es2015",
        "stage-2",
        "react"
    ],
    "plugins": [
        "transform-decorators-legacy"
    ]
}

Question

What is the difference between presets and plugins? Which one should I use to configure Babel?

回答1:

tl;dr

Presets are just a collection of plugins. You can include plugins individually in the plugins array, or collection of plugins in the presets array. If a plugin is part of a collection (preset), you don't have to include it individually in plugins.

The same goes for npm packages when you include them in package.json.

Presets vs Plugins

Babel has lots of official and third party plugins. Presets are collections of plugins or as they say:

Presets are sharable .babelrc configs or simply an array of babel plugins.

Plugins of a preset

The most common presets are the official ones and the experimental presets.

Most of the official presets contain plugins to transpile features of the EcmaScript standards, while the experimental (stage-x) presets contain plugins that transpile future experimental features whose standardization is still work in progress. Going from stage 0 (just an idea) to stage 3 (candidate) you will have collections of plugins that are more closer to getting standardized. Because of this, when you include a preset, every preset with a higher stage-x value will be included too. The plugins contained in these presets are continuously varying in each version, since they are work in progress, and there is a chance that plugins will be removed if they got rejected. That is why you need transform-decorators-legacy because, decorator transpiling was removed from Babel, although they will add it back in the future.

When you click on a preset, you can see which plugins (and maybe other presets) are included in it. If you included a plugin via a preset you don't have to include it individually. The same goes for package.json when you include the npm packages of the presets.