有没有一种方法可以为Babel插件提供自定义选项?

6

我可能错了,但我找不到任何解决方案来给我的自定义 Babel 插件提供一些自定义选项。你有什么线索可以帮助我实现这个吗?

这是我的构建过程,我使用 gulp、browserify 和 babelify:

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

我希望能够向我的插件提供一些自定义数据,类似于这样:

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/");
});

在我的插件中,我希望能够检索刚刚声明的customOptions对象。是否有一种方法可以实现这样的操作?

谢谢!

祝好!

2个回答

8

最近在 Babel 6 中有所改变。根据文档

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"
    }]
  ]
}
在Babel插件手册中,插件选项的文档。

我找不到在插件函数范围内访问插件选项的方法。似乎只能从访问器范围访问state.opts - Gajus
我没有解决方案,但我想指出有关插件选项的文档:https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#toc-plugin-options - Samuel Maisonneuve

3
我找到了一种方法,但我相信这不是一个正确的方法:
阅读babel代码,似乎有一个名为“extra”的隐藏选项。我使用该选项来推送我的自定义选项:
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/");
});

在我的插件中,我可以像这样检索我的自定义选项:
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
        }
    });
}

我知道这绝对不是一个正确的方式。你有什么替代方案吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接