【问题标题】:Is there a way to give custom options to a babel plugin?有没有办法为 babel 插件提供自定义选项?
【发布时间】:2015-06-11 09:33:33
【问题描述】:

我可能错了,但我找不到任何解决方案来为我的自定义 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 对象。有没有办法实现这样的目标?

谢谢,

问候

【问题讨论】:

    标签: javascript plugins babeljs


    【解决方案1】:

    这在 Babel 6 中最近发生了变化。来自the docs:

    插件可以指定选项。您可以通过将其包装在一个数组中并提供一个选项对象来在您的配置中执行此操作。例如:

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

    Plugin Options Babel 插件手册中的文档。

    【讨论】:

    【解决方案2】:

    我找到了一条出路,但我很确定这不是一条正确的路:

    阅读 babel 代码,似乎有一个隐藏选项,叫做“额外”。我使用该选项来推送我的自定义选项:

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

    我知道这绝对不是正确的方法。你有其他选择吗?

    【讨论】:

      猜你喜欢
      • 2014-07-16
      • 2019-04-28
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 2021-11-25
      • 2018-05-16
      相关资源
      最近更新 更多