-
Notifications
You must be signed in to change notification settings - Fork 1
/
replaceCSS.js
59 lines (46 loc) · 1.62 KB
/
replaceCSS.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
const path = require("path");
const fs = require("fs");
// replace css imports with string injection in typescript output
const lib = path.resolve(__dirname, "lib/src");
function fileID() {
const length = 12;
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
let result = "";
for (let i = 0; i < length; i++) {
result += chars[Math.floor(Math.random() * chars.length)];
}
return result;
}
function injectCSSString(file) {
// const cssSource = fs.readFileSync(file, "utf-8").replace(/\s/g, "");
const cssSource = fs.readFileSync(file, "utf-8");
const name = fileID();
return `
const ${name} = document.createElement("style");
${name}.textContent = \`${cssSource}\`;
document.head.appendChild(${name});
`;
}
function replaceCSS(dir) {
const files = fs.readdirSync(dir);
for (const file of files) {
if (fs.lstatSync(path.resolve(dir, file)).isDirectory()) {
replaceCSS(path.resolve(dir, file));
} else if (file.endsWith(".js")) {
let text = fs.readFileSync(path.resolve(dir, file), "utf-8");
const cssImportRegex = /import ("(.*).css");/g;
const matches = text.match(cssImportRegex);
if (!matches) continue;
matches.forEach((m) => {
const p = m.match(/"(.*)"/)[0];
let file = path.resolve(dir, p.substring(1, p.length - 1));
file = file.replace("/lib", "");
const injectString = injectCSSString(file);
text = text.replace(m, injectString);
console.log(`Replaced css import ('${file}') with style tag inject.`);
});
fs.writeFileSync(path.resolve(dir, file), text);
}
}
}
replaceCSS(lib);