How to feature-detect es6 modules
Use
'noModule' in HTMLScriptElement.prototype
ref
2021 Update:
While the Loader spec seems to have stalled the dynamic import alternative has been implemented by various runtimes.
Since support for modules is a prerequisite for dynamic imports the latter can be used to probe support for the former.
This doesn't rely on any DOM API specifics so it can be used in other contexts. One limitation is that it must be queried asynchronously. Another limitation is that this detection isn't compatible with unsafe-eval
CSPs, in that case probing via HTMLScriptElement
or the Worker
API can be used as fallback.
let supported = null;
async function modulesSupported() {
if (supported !== null) {
return supported;
}
try {
let module = await new Function("return (async () => {return await import('data:application/javascript,export%20let%20canary%20=%201;')})")()()
supported = module && module.canary && module.canary == 1;
} catch(e) {
supported = false;
}
return supported;
}
modulesSupported().then(r => console.log(r));
// => `true`
Old answer:
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.