dimport
Version:
Run ES Module syntax in any browser – even IE!
2 lines (1 loc) • 2.45 kB
JavaScript
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.dimport=e()}(this,function(){var t=/(^|;|\s+)import\s*['"]([^'"]+)['"](?=($|;|\s))/gi,e=/(^|[;\s]+)?import\s*(\*\s*as)?\s*(\w*?)\s*,?\s*(?:\{([\s\S]*?)\})?\s*from\s*['"]([^'"]+)['"];?/gi;function n(t,e){for(var n=[];t.length;)n.push(t.shift().trim().replace(/ as /g,":"));return"const { "+n.join(", ")+" } = "+e+";"}var r={};function o(r,o){window.dimport=i;var s,p=[],u=[],a={exports:{}},c=function(r,o){return r.replace(t,"$1"+(o=o||"require")+"('$2')").replace(e,function(t,e,r,i,s,p){return(e||"")+function(t,e,r,o){return e=o+"('"+e+"')",t.length&&!r?n(t,e):"const "+r+" = "+e+";"+(t.length?"\n"+n(t,r):"")}(s?s.split(","):[],p,i,o)})}(o.replace(/(^|\s|;)(import\s*)(\(|.*from\s*|)['"]([^'"]+)['"];?/gi,function(t,e,n,o,i){return i="'"+new URL(i,r).href+"'",e+n+o+("("==o?i:"'$dimport["+(u.push(i)-1)+"]';")}).replace(/(^|\s|;)(import)(?=\()/g,"$1window.dimport").replace(/export default/,"module.exports =").replace(/export\s+(const|function|class|let|var)\s+(.+?)(?=(\(|\s|=))/gi,function(t,e,n){return p.push(n)&&e+" "+n}).replace(/export\s*\{([\s\S]*?)\}/gi,function(t,e){for(var n,r="",o=e.split(",");n=o.shift();)r+="exports."+((n=n.trim().split(" as "))[1]||n[0])+" = "+n[0]+";\n";return r}),"eval");for(p.sort();s=p.shift();)c+="\nexports."+s+" = "+s+";";return Promise.resolve(new Function("module","exports",u.length?"return Promise.all(["+u.join()+"].map(window.dimport)).then(function($dimport){"+c+"});":c)(a,a.exports)).then(function(){return a.exports.default=a.exports.default||a.exports,a.exports})}function i(t){t=function(t,e,n,r){return/^https?:\/\//.test(t)?t:((n=document.createElement("a")).href=e,"/"==t[0]||"/"===n.pathname?n.origin+"/"+t:(r=n.pathname.split("/"),e=t.split("../"),n.origin+r.slice(0,r.length-Math.max(e.length-1,1)).concat(e.pop()).join("/")))}(t,location.href);try{return new Function("return import('"+t+"')").call()}catch(e){return r[t]?Promise.resolve(r[t]):new Promise(function(e,n,i){(i=new XMLHttpRequest).onerror=n,i.open("GET",t,!0),i.onload=function(){i.status>=400?n(new TypeError("Failed to fetch dynamically imported module: "+t)):o(t,i.responseText).then(function(n){return e(r[t]=n)})},i.send()})}}var s=void 0!==document&&document.querySelector("script[data-main]");return s&&(s.text?o(location.href,s.text):(s=s.getAttribute("data-main"))&&i(s)),i});