-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathreplace.html.js
59 lines (53 loc) · 2.18 KB
/
replace.html.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import path from "path";
import { readFileSync } from "fs";
import MagicString from "magic-string";
import { install } from "source-map-support";
/**
* @typedef {import('rollup').Plugin} Plugin
* Used to replace html template imports with the contents of the file as template string.
* Make sure to use the loadHTML function in your js files to load the html template.
* @example
* import { loadHTML } from "./replace.html.js";
* const html = await loadHTML("./my-template.html", import.meta.url);
* // will be replace by the contents of the file my-template.html
* @returns {Plugin}
*/
export function replaceHtml() {
const re = /await\s+loadHTML\(\s+"([^,]+)",\s+.+\s+\);*/g;
return {
name: "replace-html-import",
// replaces the import with the contents of the file
transform(code, id) {
function replacer(match, relativeUrl) {
const filePath = path.resolve(path.dirname(id), relativeUrl);
const html = readFileSync(filePath, { encoding: "utf8" });
return JSON.stringify(html) + "; // replaced by importmap.plugin.js";
}
// Create a new MagicString object to manipulate the code
const magicString = new MagicString(code);
let match;
while ((match = re.exec(code)) !== null) {
const start = match.index;
const end = start + match[0].length;
magicString.overwrite(start, end, replacer(match[0], match[1]));
}
// Generate a new source map
const map = magicString.generateMap({
source: id,
includeContent: true,
});
// Add the source map to the code using source-map-support
install();
// Return the modified code and source map
const annotatedCode = magicString.toString();
return { code: annotatedCode, map };
},
};
}
// from https://marian-caikovski.medium.com/how-to-import-html-template-file-into-javascript-module-265746167974
// loadHTML function is replaced by the corresponding html string using the rollup plugin widgets\importmap.plugin.js
export async function loadHTML(htmlRelativeUrl, baseUrl) {
const htmlUrl = new URL(htmlRelativeUrl, baseUrl).href;
const response = await fetch(htmlUrl);
return await response.text();
}