The applications of this plugin are wide, so it's kinda hard to sum it up, but
basically my use case was I needed to add a bunch of named exports to
glamorous (one for every DOM node type) and I didn't want to
maintain the exports in my source file. So someone created a post-build script
to concatenate them to the end of the file. I built this plugin so I could do
that without having an ad-hoc post-build script.
This plugin allows you to generate code at build-time. Any code that runs
synchronously in node can be used to generate a string of code and that string
will be inserted in place of where your usage appears.
It works by accepting your code string (or module when using the // @codegen
comment directive) and requiring it as a module. Then it takes whatever the
export was (which should be a string) and converts that string to an AST node
and swaps your usage node with the new AST node.
This module is distributed via npm which is bundled with node and
should be installed as one of your project's devDependencies:
npm install --save-dev babel-plugin-codegen
Usage
This package works in a very similar way to babel-plugin-preval
except in this case instead of any value being replaced in the code, you're
actually replacing it with code (giving you a little bit more power in exchange
for potentially being a little more confusing).
Important notes:
All code run by codegen is not run in a sandboxed environment
All code must run synchronously.
You may like to watch
this YouTube video
to get an idea of what codegen is and how it can be used.
You could also use codegen.macro if you'd prefer to type
less 😀
Caveats
One really important thing to note here is that it doesn't work by simply
replacing your code with whatever string you export. Instead it replaces it at
the AST level. This means that the resulting code should operate the same, but
the format of the code could be entirely different. Most of the time this should
not matter, but if it matters to you, please feel free to contribute back if you
feel like you could make it work!