2015-11-09 58 views
2

当涉及到自定义扩展元素的方法,如PlainJS closest() DOM元素的方法:ES6模块出口 - 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模块导入/导出?将导出放在方法定义之前会导致“意外标记这个”错误。将ES6模块系统导出为包括IIFE的最佳方法是什么?

如果目标是使用诸如.closest()这样的方法作为Element类方法,则在另一个可导出函数中进行包装看起来不正确。

谢谢你的时间。

+3

您不需要导出,你只是运行它。 'import'path/to/your/lib.js';' – zerkms

+0

使用该语法执行导入会导致假设的'lib.js'文件中的每个导出的函数被导入或者只是扩展的类方法? [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)指出“仅用于副作用,无需导入任何绑定”,但这并未真正指定。 –

+1

不,如果您不指定要导入的位置 - 则不会将任何内容导入当前作用域。 – zerkms

回答

0

您的代码将不会与模块系统一起工作 - 所有模块都以严格模式运行,因此全局这是未定义的。

你有两个选择:

  • 导出功能以Element作为参数和扩展对象。这可能是最好的选择 - 你的模块有单一的责任 - 扩展它的论点。它不会为查找全局对象引用而烦恼,它可以在任何地方使用。
  • 使用空出口,进口空和扩展全球Element

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