Using babel, how can I append some code to the top of every file?
Tip 1: the environment variable BABEL_DISABLE_CACHE=1
is needed if you are doing heavy testing of plugins. If you had a script that you ran like npm run unit
you may instead want to run like BABEL_DISABLE_CACHE=1 npm run unit
while testing your plugin.
Tip 2: babel.parse
will give you a full program out of some source. The easiest thing you could do is babel.parse(header).program.body[0]
.
The following ended up working:
function injectDefine(babel) {
var header = 'if (typeof define !== "function") { var define = require("amdefine")(module); }';
return new babel.Plugin('amdefine', {
visitor: {
Program: {
enter: function(node, parent) {
node.body.unshift(
babel.parse(header).program.body[0]
);
},
},
},
});
}
require('babel-core/register')({
cache: false,
stage: 0,
plugins: [injectDefine],
});