How to feature-detect es6 modules

2020-02-24 13:08发布

问题:

I'd like to export a module using the ES6 syntax only if it is supported in the current runtime. The goal is to develop a library that support different module management systems.

As export is a keyword, something like will throw a syntax error :

typeof export

回答1:

Revision 27 of the spec had a Reflect.Loader API that could be used for module reflection.

While that isn't direct feature detection for the export keyword in itself, it might have been possible to load a module that uses export keywords from a data-uri and then check whether it throws parse errors or not.

But it has been removed with revision 28, with the following changelog entry:

Removed loader pipeline and Reflect.Loader API (functionality being transferred to separate specification)


Thus, as far as i can tell, the spec does not seem to provide any way of feature detection at the time of writing.

In the future it might be possible with Reflect.Loader or its replacements.

Edit: The loader spec seems to be developed managed by the whatwg, but it's not yet in a state from which we could derive feature detection.



回答2:

Use


'noModule' in HTMLScriptElement.prototype

ref



回答3:

Check for the 'noModule' attribute:

document.currentScript && "noModule" in document.currentScript;