-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatch.js
56 lines (45 loc) · 1.59 KB
/
watch.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
const fs = require("fs");
const fsAsync = require("fs/promises");
const path = require("path")
const COMPONENTS_PATH = path.join(__dirname, "/src/scripts/components");
const SNIPPETS_PATH = path.join(__dirname, "/snippets");
const FILE_PATH = path.join(SNIPPETS_PATH, "/component-loader.liquid")
const mode = process.env.NODE_ENV || "development";
populateComponents();
mode === "development" && watch();
function watch() {
fs.watch(COMPONENTS_PATH, async (eventType, filename) => {
if (eventType === "rename") {
await populateComponents();
}
});
}
async function populateComponents() {
const files = await getComponents();
const components = {};
files.forEach((file) => {
components[file] = getAssetUrl(file);
});
await writeSnippet(components);
return components;
}
async function getComponents() {
const files = await fsAsync.readdir(COMPONENTS_PATH);
return files.filter(file => file.includes("js")).map((file) => file.replace(".js", ""));
}
function getAssetUrl(name) {
return `{{ 'js-component-${name}.min.js' | asset_url }}`;
}
async function writeSnippet(components) {
let content = await (await fsAsync.readFile(FILE_PATH, "utf8")).toString();
const file = `window.components = ${JSON.stringify(components, null, 2)}`;
const newContent = content.replace(new RegExp(/<script\b[^>]*>([\s\S]*?)<\/script>/), `<script>\n\t${file}\n</script>`)
if (newContent === content) {
console.log("NO CHANGES")
return;
}
fs.writeFile(FILE_PATH, newContent, (err) => {
if (err) console.log(err);
else console.log("Components list is generated!");
});
}