Detect ES6 import compatibility
Asked Answered
G

2

7

I understand that you can detect features in javascript with something like this

if(xmlhttprequest){
console.log("this browser is ajax compatible");
}

I also understand that ES6 imports are nativly compatable with some browsers if certain dev mode settings are enabled. ie

import {someExport} from './someModule.js';

My question is

Is it possible to feature detect "Import" in the like you would an object? if yes, How can it be done? Is it possible to import whole JS file (so that an ES5 Javascript which does not use Export can be imported)

I have attempted using the if(object) syntax with various variations (including with and without a from statement) but so far have had no luck

My reason for this i I have build a javascript feature which relies on Jquery and GreenSock and want the script to import these automatically in compatible browsers so the developer does not have to manually add multiple JS libraries.

Gunnar answered 3/7, 2017 at 17:45 Comment(1)
See also How to feature-detect es6 modules (for exports)Ablution
O
17

It is safe to assume that all browsers that support ES6-style module import/export syntax can load modules through script tags using type="module". Those browsers also offer an attribute for script tags called nomodule. You can therefore detect support from within JavaScript as follows:

'noModule' in HTMLScriptElement.prototype

(note the uppercase 'M' in the property name as opposed to the HTML attribute)

Oppress answered 30/7, 2018 at 20:37 Comment(0)
Y
2

Have you considered using the nomodule attribute on script?

Example

<script type="module">
  window.imports = true;
  import './app-shell-es.js';
</script>

<script src="app-shell.js" nomodule></script>

Source: ECMAScript modules in browsers

Youmans answered 6/9, 2017 at 18:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.