Is there a way to give custom options to a babel plugin?

2.6k views Asked by At

I might be wrong but i couldn't find any solution to give some custom options to my custom babel plugin. Do you have any clue how i could achieve this ?

Here is my building process, i'm using gulp with browserify and babelify :

gulp.task("scripts", function() {
    return browserify({
        entries: "myFile.js"
    })
    .transform(babelify.configure({
        plugins: ["./lib/myPlugin:after"]
    }))
    .bundle()
    .pipe(source("all.js"))
    .pipe("build/");
});

I would like to give some custom data to my plugin, doing something like this :

gulp.task("scripts", function() {
    return browserify({
        entries: "myFile.js"
    })
    .transform(babelify.configure({
        myCustomOptions: {
            rootPath: "some path",
            customInfo: "..."
        }
        plugins: ["./lib/myPlugin:after"]
    }))
    .bundle()
    .pipe(source("all.js"))
    .pipe("build/");
});

Then in my plugin, i would like to retrieve the customOptions object i just declared. Would there be a way to achieve something like that ?

Thanks,

Regards

2

There are 2 answers

2
mik01aj On BEST ANSWER

This has changed recently in Babel 6. From the docs:

Plugins can specify options. You can do so in your config by wrapping it in an array and providing a options object. For example:

{
  "plugins": [
    ["transform-async-to-module-method", {
      "module": "bluebird",
      "method": "coroutine"
    }]
  ]
}

Plugin Options documentation in the Babel plugin handbook.

0
Samuel Maisonneuve On

I found a way out but i'm pretty sure it's not a proper way to go :

Reading babel code, it seems there is a hidden option called "extra". I used that option to push my custom options :

gulp.task("scripts", function() {
    return browserify({
        entries: "myFile.js"
    })
    .transform(babelify.configure({
        extra: {
            myPlugin: {
                // here i put my custom data
            }
        },
        plugins: ["./lib/myPlugin:after"]
    }))
    .bundle()
    .pipe(source("all.js"))
    .pipe("build/");
});

Then in my plugin i can retrieve my custom options like this :

var myPlugin = function(babel) {
    var t = babel.types;
    var pluginConf;

    return new babel.Transformer("babel-platform", {
        CallExpression(node, parent, scope, config) {
            pluginConf = pluginConf || config.opts.extra["myPlugin"] || {};
            // Doing some stuff here on the CallExpression
        }
    });
}

I know this is definitely not a proper way. Would you have any alternatives ?