Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active October 19, 2024 12:44
Show Gist options
  • Save WebReflection/5fc85856bba3d6eef794877fb5fa2a52 to your computer and use it in GitHub Desktop.
Save WebReflection/5fc85856bba3d6eef794877fb5fa2a52 to your computer and use it in GitHub Desktop.

A Runtime ImportMap Example - now as a module

While it's not possible to define a <script type="importmap"> within a module, it is possible to define it in a synchronous <script> tag, as long as it's before any module starts executing.

Example (works in Chrome / Edge / WebKit / Safari / Firefox)

<!DOCTYPE html>
<html lang="en">
<head>
  <!-- a synchronous script -->
  <script>
  (() => {
    // any needed import path
    const imports = {
      'vanilla-elements': 'https://cdn.skypack.dev/vanilla-elements/'
    };

    // any useful feature detection (builtin extends in this case)
    try {
      class Script extends HTMLScriptElement {}
      customElements.define('no-💩', Script, {extends: 'script'});
      new Script;
    }
    catch (o_O) {
      imports['vanilla-elements'] = 'https://cdn.skypack.dev/vanilla-elements/poly';
    }

    // the importmap script
    const script = document.createElement('script');
    script.type = 'importmap';
    script.textContent = JSON.stringify({imports});
    document.head.appendChild(script);
  })();
  </script>

  <!-- any module -->
  <script type="module">
  import {define, HTML} from 'vanilla-elements';
  define('hello-world', class extends HTML.Body {
    connectedCallback() {
      this.innerHTML = '<h1>Hello World 👋</h1>';
    }
  });
  </script>
</head>
<body is="hello-world"></body>
</html>
@WebReflection
Copy link
Author

WebReflection commented Oct 18, 2024

A terser version based on <script> tag to put on top of the head or before other scripts:

<script imports="one,or-more,@module/entry">
((m,a,p)=>{
	for (let s of m.getAttribute('imports').split(/,\s*/))a[s]=p+s;
	m.replaceWith(Object.assign(
		document.createElement('script'),
		{type:'importmap',textContent:JSON.stringify({imports:a})}
	));
})(document.currentScript,{},'https://esm.run/');
</script>

@WebReflection
Copy link
Author

WebReflection commented Oct 18, 2024

This is now a module

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment