Javascript ES6模块导出-DOM元素扩展方法

Javascript ES6模块导出-DOM元素扩展方法,javascript,ecmascript-6,Javascript,Ecmascript 6,当涉及到自定义扩展元素方法时,如PlainJS DOM元素方法: // closest polyfill this.Element && function(ElementPrototype) { ElementPrototype.closest = ElementPrototype.closest || function(selector) { var el = this; while (el.matches &&

当涉及到自定义扩展元素方法时,如PlainJS DOM元素方法:

// closest polyfill
this.Element && function(ElementPrototype) {
    ElementPrototype.closest = ElementPrototype.closest ||
    function(selector) {
        var el = this;
        while (el.matches && !el.matches(selector)) el = el.parentNode;
        return el.matches ? el : null;
    }
}(Element.prototype);
通过ES6模块导入/导出导出和导入扩展方法(如此)的最安全方式是什么?将导出放在方法定义前面会导致“意外标记此”错误。将IIFE导出到ES6模块系统的最佳方法是什么

如果目标是使用诸如
.closest()
之类的方法作为元素类方法,那么封装在另一个可导出函数中似乎是不正确的


谢谢您的时间。

您的代码无法与模块系统一起工作-所有模块都在严格模式下运行,因此全局模式未定义

您有两个选择:

  • 导出以
    元素
    为参数的函数,并扩展该对象。这可能是最好的选择-你的模块只有一个职责-扩展它的参数。它不必费心寻找全局对象的引用,它可以在任何地方工作
  • 使用空导出、空导入和扩展全局
    元素
polyfill.js
中:

if (typeof Element === 'function') {
    Element.prototype.closest = ...
}
export {}; // empty export to signal to your module loader that's ES6 module
在main.js中:

import 'polyfill.js'; // import for side-effects only

您不需要导出它,只需运行它<代码>导入'path/to/your/lib.js'使用该语法执行导入会导致导入假设的
lib.js
文件中的每个导出函数,还是只导入扩展类方法?指示“仅用于副作用,不导入任何绑定”,但这并没有真正指定。不,如果不指定导入位置,则不会将任何内容导入到当前范围。