Skip to content

Instantly share code, notes, and snippets.

@Willmo36
Created July 20, 2023 19:51
Show Gist options
  • Save Willmo36/ae5665cdd520774c24870250651dd410 to your computer and use it in GitHub Desktop.
Save Willmo36/ae5665cdd520774c24870250651dd410 to your computer and use it in GitHub Desktop.
ImportMap module federation
<html>
<body>
<script type="importmap">
{
"imports": {
"moduleA": "/moduleA.js",
"moduleB": "/moduleB.js",
"react": "https://esm.sh/react@17"
},
"scopes": {
"http://localhost:3334": {
"moduleA": "http://localhost:3334/moduleA.js",
"moduleB": "http://localhost:3334/moduleB.js",
"react": "https://esm.sh/react@17"
}
}
}
</script>
<script type="module" src="moduleB.js"></script>
<script type="module" src="http://localhost:3334/moduleB.js"></script>
</body>
</html>
export function foo() {
console.log(`Hello from ${import.meta.url}`);
}
import {foo} from "moduleA"
import * as React from "react";
foo();
console.info(`${import.meta.url} imported React ->`, React);
console.info('-----')
@Willmo36
Copy link
Author

Willmo36 commented Jul 20, 2023

  1. Run 2 HTTP servers on ports 3333 & 3334
  2. Open localhost:3333 with console open
  3. The React module will be logged twice, once from each domain
  4. Right both of the React modules -> store as global object (usually temp1 & temp2)
  5. Run equality check (temp1 === temp2)
  6. If using the same React version, the same instance is used between the scripts. Also React is downloaded once, not twice.

CleanShot 2023-07-20 at 13 57 20@2x

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