如何以编程方式将选项传递给 Babel transforms/plugins?

How to programmatically pass options to Babel transforms/plugins?

我使用的一个工具以编程方式使用 Babel。它只需要很少的插件,一切正常。

不过,我想将选项传递给 Babel 转换。我意识到我还没有这样做,看起来我正在尝试的方法不起作用。

具体来说,我想包含 babel-transform-strict-mode 并传递 strict:false 以禁用全局严格模式。

文档解释了在有 .babelrc 文件时如何使用它:

// with options
{
  "plugins": [
    ["transform-strict-mode", {
      "strict": true
    }]
  ]
}

在我的代码中我有:

const babelify = require("babelify")
    , es2015 = require("babel-preset-es2015")
    , reactify = require("babel-preset-react")
    , strictMode = require("babel-plugin-transform-strict-mode")
    ;

...

this.browserify.transform(babelify, {
    global: true,
    babelrc: false,
    presets: [
        reactify
      , es2015
      , [
            strictMode
          , { strict: false }
        ]
    ] 
});

虽然 es2015reactifypresets 数组中工作得很好,但添加 strictMode{ strict: false } 只是行不通。

错误是:

ReferenceError: [BABEL] /home/.../index.js: Unknown option: foreign.visitor.
Check out http://babeljs.io/docs/usage/options/ for more
information about options.

A common cause of this error is the presence of a
configuration options object without the corresponding
preset name. Example:

Invalid:
  `{ presets: [{option: value}] }`
Valid:
  `{ presets: [['presetName', {option: value}]] }`

For more detailed information on preset configuration,
please see
http://babeljs.io/docs/plugins/#pluginpresets-options.

如果我不使用 strictMode 转换名称 (["transform-strict-mode", { strict: false }]),它显然找不到模块,因为这是另一个模块的一部分。

如何以编程方式(没有 babelrc)将选项传递给 required 模块(在本例中为 strictMode)?

babel-plugin-transform-strict-mode是一个插件,不是预设组件,所以你必须在plugins选项中设置插件。

this.browserify.transform(babelify, {
global: true,
babelrc: false,
presets: [
    reactify
  , es2015
],
plugins:[
  [
        strictMode
      , { strict: false }
    ]
]

});

通常这里推荐的方法是禁用 ES6 模块支持,因为 ES6 模块是自动严格的。例如

this.browserify.transform(babelify, {
  sourceType: 'script',
  presets: [
    reactify,
    [es2015, {modules: false}],
  ],
})

在您的具体情况下,由于您的问题破坏了 node_modules,这是因为您使用了 global: true

我假设你特地通过 global: true 因为你有 node_modules 容器 ES6?如果是这样,您应该通过为 babelify 指定 ignore 正则表达式来将编译的内容列入白名单,例如:

// ...
global: true,
ignore: /node_modules\/(?:some_es6_module|some_other_es6_module)/,
// ...

忽略路径中包含 node_modules 的任何文件,但名为 some_es6_modulesome_other_es6_module 的模块除外。这样 underscore 之类的东西就不会受到影响。