What's transforms and plugins?

Custom plugins enable users to extend the base official functionality of Babel - for transpilers this means some pluggable transforms. So what exactly is a transform?

If you're advanced enough, you may know about abstract syntax trees (ASTs) and how to manipulate them. This is exactly what Babel plugins do, but this topic is way too advanced and may take another course to cover in depth. So let's try to put it simply. Babel plugins are functions that simply take code in a format that is easy to operate on and outputs another code, based on logic provided by a developer.

Let's look at an example, starting with babel-plugin-lodash, which changes wildcard imports like import _ from 'lodash' or import { map, merge } from 'lodash' to make them more precise, for example import map from 'lodash/map' and import merge from 'lodash/merge', by finding their usages in the code. Why is this needed? Because with CommonJS modules, import of any function from lodash directly takes all lodash internals to the bundle. So to optimize that without affecting the code, this plugin comes in to save the day. You may argue, - "But isn't it will be handled automatically? Lodash is mega popular, isn't it not comes in ES Modules format that handles it all automatically?". And you will be right, about your assumption, as most of the libraries do support both CJS and ESM, but not lodash, to have lodash in ES Modules format, you need to install and import lodash-es package. Why it's two different packages? I have no idea, but this is how it is. Either way hopefully these particular optimizations will soon be obsolete as Parcel, Webpack and Rollup have all introduced CommonJS tree-shaking functionality in their latest versions.

Shall we do another example of the plugin? There is also a babel-plugin-polished and babel-plugin-styled-components which make some dynamic code static if it's possible to predict. A good example would be lighten or darken functions, which lighten or darken original color by a percentage. So code like:

Start a new discussion. All notification go to the author.