检测ES6导入兼容性 [英] Detect ES6 import compatibility

查看:102
本文介绍了检测ES6导入兼容性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解您可以通过以下方式检测javascript中的功能

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

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

我还理解,如果启用了某些开发模式设置,则ES6导入可以与某些浏览器自然兼容.即

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';

我的问题是

是否有可能像检测对象一样对导入"进行特征检测? 如是, 怎么做到呢? 是否可以导入整个JS文件(以便可以导入不使用Export的ES5 Javascript)

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)

我尝试使用if(object)语法进行各种修改(包括使用和不使用from语句),但是到目前为止还算不上运气

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

我这样做的原因是,我已经构建了一个依赖于Jquery和GreenSock的javascript功能,并希望脚本在兼容的浏览器中自动将它们导入,因此开发人员不必手动添加多个JS库.

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.

推荐答案

可以肯定地说,所有支持ES6样式模块导入/导出语法的浏览器都可以使用type="module"通过脚本标签加载模块.这些浏览器还提供了名为nomodule的脚本标签的属性.因此,您可以通过以下方式从JavaScript中检测支持:

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

(请注意,属性名称中的大写字母"M"与HTML属性相对)

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

这篇关于检测ES6导入兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆