编程语言
首页 > 编程语言> > javascript – 将白名单选项与Babel的外部助手一起使用

javascript – 将白名单选项与Babel的外部助手一起使用

作者:互联网

我正在尝试将Rollup与Babel的外部助手一起使用.它有效,但它正在丢弃一些我甚至不需要的babel助手,例如asyncGenerator.

文档show a whitelist option,但我不能让它工作

rollup.rollup({
    entry: 'src/buttonDropdown.es6',
    plugins: [
        babel({
            presets: ['react', ['es2015', { modules: false }], 'stage-2'],
            plugins: [['external-helpers', { whitelist: ['asyncGenerator'] }]]
        })
    ]
})

上面没有任何效果:所有Babel助手仍然被放入我的结果包中.

使用此功能的正确方法是什么,是否有完整的列表,列出了白名单数组的帮助者名称?

或者是否有一些其他Rollup插件我应该与Rollup一起使用以自动“树摇”babel外部助手.

解决方法:

问题

babel-plugin-external-helpers插件不负责在最终捆绑中注入这些依赖项.
它控制的唯一事情是生成的代码将如何访问这些函数.例如:

classCallCheck(this, Foo);
// or
babelHelpers.classCallCheck(this, Foo);

这是必需的所以rollup-plugin-babel需要做的就是在每个模块中注入babelHelpers.

该文档具有误导性,白名单选项不在外部助手插件上.它在completely separate module and command line tool called babel-external-helpers,实际上负责生成babelHelpers.

这是rollup-plugin-babel什么是注射babelHelpers.它是否使用技巧来模块化最终代码.它称babel-external-helpers生成帮助者,and ignores the whitelist parameter.见my issue requesting to expose an option.

这种方法是正确的,因为汇总会破坏未使用的辅助函数.但是,如果初始化有任何副作用,一些辅助程序(如asyncGenerator)的编写方式很难检测,从而防止在树抖动期间删除.

解决方法

我在forked rollup-plugin-babel创建了一个PR,它暴露了在插件选项中构建babelHelpers的白名单选项.它可以这样使用:

require("rollup").rollup({
  entry: "./src/main.js",
  plugins: [
    require("rollup-plugin-babel")({
      "presets": [["es2015", { "modules": false }]],
      "plugins": ["external-helpers"],
      "externalHelpersWhitelist": ['classCallCheck', 'inherits', 'possibleConstructorReturn']
    })
  ]
}).then(bundle => {
  var result = bundle.generate({
    format: 'iife'
  });
  require("fs").writeFileSync("./dist/bundle.js", result.code);
}).then(null, err => console.error(err));

请注意,我没有在npm上发布分发版本,你必须克隆git repo并使用rollup -c构建它.

在我看来,正确的解决方案是以某种方式检测或告诉汇总这些出口是纯净的,因此可以通过树摇动来消除.在做了一些研究之后,我将在github上开始讨论它.

标签:javascript,babeljs,rollupjs
来源: https://codeday.me/bug/20190611/1218745.html