Last active
December 17, 2021 22:33
-
-
Save ziadkh0/ae6cc847663fdc3898e51303f1c5a66d to your computer and use it in GitHub Desktop.
ES Module shims loader for intern (https://github.com/theintern/intern)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
'use strict'; | |
intern.registerLoader(function(options) { | |
if (intern.environment !== 'browser') { | |
throw new Error('The ES Module Shims loader only works in the browser'); | |
} | |
if (typeof options.esModulesShims !== 'string') { | |
throw new Error( | |
'The ES Module Shims loader requires "esModulesShims" to be of type ' + | |
'string' | |
); | |
} | |
intern.log('Initializing ES Module Shims loader with:', options); | |
function resolveUrl(url) { | |
if (url[0] !== '/' && !/https?:\/\//.test(url)) { | |
url = `${intern.config.basePath}${url}`; | |
} | |
return url; | |
} | |
function addImportMap(srcOrObject) { | |
const scriptTag = document.createElement('script'); | |
scriptTag.type = 'importmap-shim'; | |
if (typeof srcOrObject === 'string') { | |
scriptTag.src = resolveUrl(srcOrObject); | |
} else { | |
scriptTag.text = JSON.stringify(srcOrObject); | |
} | |
const scriptTarget = document.head || document.body; | |
scriptTarget.appendChild(scriptTag); | |
} | |
async function importModule(url) { | |
return window.importShim(resolveUrl(url)); | |
} | |
if (options.importMaps) { | |
if (!Array.isArray(options.importMaps)) { | |
if ( | |
typeof options.importMaps === 'string' || | |
typeof options.importMaps === 'object' | |
) { | |
options.importMaps = [options.importMaps]; | |
} else { | |
throw new Error( | |
'The ES Module Shims loader requires "importMaps", if given, to ' + | |
'be of a single (URL of the import map), and object (the import ' + | |
'map itself) or an array of either' | |
); | |
} | |
} | |
options.importMaps.forEach(addImportMap); | |
} | |
return intern.loadScript(options.esModulesShims).then(function() { | |
intern.log('Using ES Module Shims loader'); | |
return function(modules) { | |
return Promise.all(modules.map(importModule)); | |
}; | |
}); | |
}); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment