Using Babel Plugin Macros
Gatsby includes a powerful new way of applying compile-time code transformations, Babel macros! Macros are like Babel plugins, but instead of adding them to your
.babelrc, you import them in the file you want to use them. This has two big advantages:
- No confusion about where a non-standard syntax is coming from. Macros are explicitly imported wherever they are used.
- No configuration files. Macros are included directly in your code as needed.
Just like plugins, many macros are published as npm packages. By convention, they are named by their function, followed by
Some macros are instead included in larger packages. To install and use them, refer to their documentation.
To use an installed macro, import it in your code like so:
You can then use the imported variable however the macro’s documentation says.
preval.macro is used as a template literal tag:
When building your project this code will be transformed into:
Take a look at the Awesome babel macros list to find available macros you can use. Additionally, this list contains helpful resources for using macros and developing them yourself.