Skip to content

Instantly share code, notes, and snippets.

@jmm
Created June 16, 2015 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmm/8f3fe314a1f7388f3847 to your computer and use it in GitHub Desktop.
Save jmm/8f3fe314a1f7388f3847 to your computer and use it in GitHub Desktop.
Demo of issue with creating babel plugin to dynamically insert `import` declaration. See babel/babel#1777
var
babel = require('babel'),
output;
function plugin (babel) {
var t = babel.types;
var transformers = {
Program: {
enter: function (node) {
var newImport = t.importDeclaration(
[t.importDefaultSpecifier(t.identifier("x"))],
t.literal("x")
);
this.unshiftContainer('body', newImport);
}
}
};
return new babel.Transformer('plugin', transformers);
}
// plugin
output = babel.transform(
"x();",
{
plugins: [plugin],
}
).code;
console.log(output);
console.log("****************************************");
output = babel.transform(
"import x from 'x'; x();",
{
}
).code;
console.log(output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment