Babel Plugin Macros

Gatsby also permits the use of Babel macros to apply compile-time code transformations that can be more flexible than Babel plugins. Rather than including them in the .babelrc configuration file, we insert Babel plugin macros into the working code of the files we write. Babel macros have two key advantages:

  • There is no uncertainty about where particular nonstandard or noncompliant syntax is originating from, as macros are explicitly imported in the places they are used.
  • There is no need for configuration files, as macros are included in code directly on only an as-needed basis.

Because Babel plugin macros run only at compile time, like Babel plugins themselves, they are unavailable in the publicly distributed JavaScript bundle. Therefore, these macros have no impact other than the transformations they are responsible for.

Like Babel plugins, many macros are available in the JavaScript ecosystem as packages. The convention for community macros is to suffix the name of the macro, typically a description of its function, with .macro. For example, preval.macro is a macro that forces the preevaluation of the code it is responsible for. We can install this macro into our development dependencies as follows:

$ npm install --save-dev preval.macro

We can then import the macro and use it with a template literal tag to perform certain logic. For example, the following code:

import preval from "preval.macro"
const y = preval`module.exports = 2`

will yield this transformed code in the resulting project build:

const y = 2
NOTE

For more information about Babel macros, consult the Babel plugin macros documentation. The awesome-babel-macros repository also contains useful information about macros and macro development.


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *