@@ -22,13 +22,19 @@ export const writeIntoFiles = (
2222 const importmapAsJson = JSON . stringify ( importmap , null , " " ) ;
2323 if ( fileUrl . endsWith ( ".html" ) ) {
2424 writeIntoHtmlFile ( fileUrl , importmapAsJson , { logger } ) ;
25+ } else if ( fileUrl . endsWith ( ".js" ) ) {
26+ writeInfoJsFile ( fileUrl , importmapAsJson , { logger } ) ;
2527 } else {
26- writeFileSync ( fileUrl , importmapAsJson ) ;
27- logger . info ( `-> ${ urlToFileSystemPath ( fileUrl ) } ` ) ;
28+ writeIntoJsonFile ( fileUrl , importmapAsJson , { logger } ) ;
2829 }
2930 }
3031} ;
3132
33+ const writeIntoJsonFile = ( jsonFileUrl , importmapAsJson , { logger } ) => {
34+ writeFileSync ( jsonFileUrl , importmapAsJson ) ;
35+ logger . info ( `-> ${ urlToFileSystemPath ( jsonFileUrl ) } ` ) ;
36+ } ;
37+
3238const writeIntoHtmlFile = ( htmlFileUrl , importmapAsJson , { logger } ) => {
3339 const htmlAst = parseHtml ( {
3440 html : readFileSync ( htmlFileUrl , { as : "string" } ) ,
@@ -80,3 +86,38 @@ const writeIntoHtmlFile = (htmlFileUrl, importmapAsJson, { logger }) => {
8086 const html = stringifyHtmlAst ( htmlAst ) ;
8187 writeFileSync ( new URL ( htmlFileUrl ) , html ) ;
8288} ;
89+
90+ const writeInfoJsFile = ( jsFileUrl , importmapAsJson , { logger } ) => {
91+ const jsFileContent = `
92+ const currentScript = document.currentScript;
93+ if (!currentScript) {
94+ throw new Error(
95+ "document.currentScript is not available, cannot inject importmap"
96+ );
97+ }
98+ const baseUrl = new URL(".", currentScript.src).href;
99+ const importmap = ${ importmapAsJson } ;
100+ const topLevelMappings = importmap.imports;
101+ const scopedMappings = importmap.scopes;
102+ const makeMappingsAbsolute = () => {
103+ for (const key of Object.keys(mappings)) {
104+ mappings[key] = baseUrl + mappings[key];
105+ }
106+ }
107+ if (topLevelMappings) {
108+ makeMappingsAbsolute(topLevelMappings);
109+ }
110+ if (scopedMappings) {
111+ for (const scope of Object.keys(scopedMappings)) {
112+ const mappings = scopedMappings[scope];
113+ makeMappingsAbsolute(mappings);
114+ }
115+ }
116+ const importmapScript = document.createElement("script");
117+ importmapScript.type = "importmap";
118+ importmapScript.textContent = importmap;
119+ currentScript.after(importmapScript);
120+ ` ;
121+ writeFileSync ( jsFileUrl , jsFileContent ) ;
122+ logger . info ( `-> ${ urlToFileSystemPath ( jsFileUrl ) } ` ) ;
123+ } ;
0 commit comments