Skip to content
Branch: master
Find file Copy path
Find file Copy path
7 contributors

Users who have contributed to this file

@kentcdodds @tylerthehaas @sw-yx @mvasilkov @stevemao @johannes-scharlach @MichaelDeBoey
127 lines (96 sloc) 3.49 KB

babel-plugin-macros Usage for users

See also: the author docs.

Adding the plugin to your config

Via .babelrc (Recommended)


  "plugins": ["macros"]

Via babel.config.js


module.exports = function (api) {
  return {
    plugins: ['macros'],


babel --plugins babel-plugin-macros script.js

Via Node API

require('babel-core').transform('code', {
  plugins: ['macros'],

Using a macro

With the babel-plugin-macros plugin added to your config, we can now use a macro that works with the babel-plugin-macros API. Let's assume we have such a module in our project called eval.macro.js. To use it, we import or require the macro module in our code like so:

import MyEval from './eval.macro'
// or
const MyEval = require('./eval.macro')

Then we use that variable however the documentation for the macro says. Incidentally, eval.macro.js actually exists in the tests for babel-plugin-macros here and you can see how it transforms our code in the babel-plugin-macros snapshots.

Note here that the real benefit is that we don't need to configure anything for every macro you add. We simply configure babel-plugin-macros, then we can use any macro available. This is part of the benefit of using babel-plugin-macros.

Using with create-react-app

Checkout the CRA Macro Example repo

babel-plugin-macros ships with react-scripts 2.0! This is awesome because it allows for babel to be configured in a nice way without having to eject from create-react-app!

Before deciding to use this however you should be aware of a few things:

  1. Features may be broken or not work as expected
  2. Documentation for new features is still sparse, so look through the pull requests for how they're expected to work

With that being said you can use all the awesomeness of babel-plugin-macros inside create-react-app by running one of the following commands based on your situation.

$ # Create a new application
$ npx create-react-app my-app
$ # Upgrade an existing application
$ yarn upgrade react-scripts


There is a feature that allows you to configure your macro. We use cosmiconfig to read a babel-plugin-macros configuration which can be located in any of the following files up the directories from the importing file:

  • .babel-plugin-macrosrc
  • .babel-plugin-macrosrc.json
  • .babel-plugin-macrosrc.yaml
  • .babel-plugin-macrosrc.yml
  • .babel-plugin-macrosrc.js
  • babel-plugin-macros.config.js
  • babelMacros in package.json

You need to specify your configName. EG: For configuring styled-components macro, the configName is "styledComponents":

// babel-plugin-macros.config.js
module.exports = {
  // ...
  // Other macros config
  styledComponents: {
    pure: true,
You can’t perform that action at this time.