Skip to content

Commit

Permalink
feat: add toHTML function
Browse files Browse the repository at this point in the history
  • Loading branch information
digitalsadhu committed Oct 9, 2024
1 parent 6738052 commit 4576ddd
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -294,4 +294,35 @@ export default class Eik {
'Eik config was not loaded or "loadMaps" is "false" when calling .maps()',
);
}

/**
* Function that generates and returns an import map script tag for use in an document head.
*
* Currently only a single import map is supported in the browser so we need to merge together import map objects into a single object
* by using a JS Map object. Last in wins so order of import maps defined in eik.json is important if multiple maps share the same entries.
*
* @example
* ```
* const importMap = eik.toHTML();
*
* <head>
* ...
* ${importMap}
* ...
* </head>
* ```
*
* @returns {string}
*/
toHTML() {
const allImportMapKeyValuePairs = this.maps().flatMap((map) =>
Object.entries(map.imports),
);
const mergedAndDedupedImportMapObject = Object.fromEntries(
new Map(allImportMapKeyValuePairs).entries(),
);
return `<script type="importmap">${JSON.stringify({
imports: mergedAndDedupedImportMapObject,
})}</script>`;
}
}
20 changes: 20 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -342,3 +342,23 @@ tap.test(
t.end();
},
);

tap.test(
"Client - toHTML - import maps merged and script tag created",
async (t) => {
const client = new Eik({
loadMaps: true,
path: t.context.fixture,
});
await client.load();

const resolved = client.toHTML();

t.same(
resolved,
`<script type="importmap">${JSON.stringify({ imports: { eik: "/src/eik.js" } })}</script>`,
"Should return an import map script tag",
);
t.end();
},
);

0 comments on commit 4576ddd

Please sign in to comment.