问题
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.
回答1:
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)
回答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
回答3:
No, it's not possible. The reason it isn't possible is because it would throw a syntax error in browsers which don't support it and you can't react properly to a syntax error.
Instead, you should use something like Webpack in conjunction with Babel to compile your code which uses modules into a format that any browser can run.
来源:https://stackoverflow.com/questions/44891421/detect-es6-import-compatibility