dimport
Version:
Run ES Module syntax in any browser – even IE!
2 lines (1 loc) • 2.08 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 r(t,e){for(var r=[];t.length;)r.push(t.shift().trim().replace(/ as /g,":"));return"const { "+r.join(", ")+" } = "+e+";"}var n={};function o(n,o){window.dimport=i;var s,u=[],p=[],c={exports:{}},f=function(n,o){return n.replace(t,"$1"+(o=o||"require")+"('$2')").replace(e,function(t,e,n,i,s,u){return(e||"")+function(t,e,n,o){return e=o+"('"+e+"')",t.length&&!n?r(t,e):"const "+n+" = "+e+";"+(t.length?"\n"+r(t,n):"")}(s?s.split(","):[],u,i,o)})}(o.replace(/(^|\s|;)(import\s*)(\(|.*from\s*|)['"]([^'"]+)['"];?/gi,function(t,e,r,o,i){return i="'"+new URL(i,n).href+"'",e+r+o+("("==o?i:"'$dimport["+(p.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,r){return u.push(r)&&e+" "+r}).replace(/export\s*\{([\s\S]*?)\}/gi,function(t,e){for(var r,n="",o=e.split(",");r=o.shift();)n+="exports."+((r=r.trim().split(" as "))[1]||r[0])+" = "+r[0]+";\n";return n}),"eval");for(u.sort();s=u.shift();)f+="\nexports."+s+" = "+s+";";return Promise.resolve(new Function("module","exports",p.length?"return Promise.all(["+p.join()+"].map(window.dimport)).then(function($dimport){"+f+"});":f)(c,c.exports)).then(function(){return c.exports.default=c.exports.default||c.exports,c.exports})}function i(t){t=new URL(t,location.href).href;try{return new Function("return import('"+t+"')").call()}catch(e){return n[t]?Promise.resolve(n[t]):fetch(t).then(function(t){return t.text()}).then(o.bind(o,t)).then(function(e){return n[t]=e})}}var s=void 0!==document&&document.currentScript||document.querySelector("script[data-main]");return s&&(s.text?o(location.href,s.text):(s=s.getAttribute("data-main"))&&i(s)),i});