See also: the
authordocs.
.babelrc
{
"plugins": ["macros"]
}Via babel.config.js
babel.config.js
module.exports = function (api) {
return {
plugins: ['macros'],
}
}babel --plugins babel-plugin-macros script.jsrequire('babel-core').transform('code', {
plugins: ['macros'],
})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 usingbabel-plugin-macros.
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:
- Features may be broken or not work as expected
- 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.jsbabel-plugin-macros.config.jsbabelMacrosinpackage.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,
},
}