-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
101 lines (83 loc) · 2.83 KB
/
index.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
'use strict';
const fs = require('fs');
const path = require('path');
const templateRegex = /template.*href="(.*\.html)"/;
function loadFile(filePath) {
let res;
try {
res = fs.readFileSync(filePath, 'utf8');
} catch (err) {
console.warn('no local file named: ', filePath);
}
return res;
}
function createFileRecursively(filePath, fileMarkup, files, compiledFiles) {
const lines = fileMarkup.split('\n');
const newLines = [];
const componentPath = filePath.match(/^(.*[\\\/])/)[0];
lines.forEach(line => {
const template = line.match(templateRegex);
if (template) {
const templatePath = `${componentPath}${template[1]}`;
const compiledFile = compiledFiles[templatePath];
if (!compiledFiles[templatePath]) {
createFileRecursively(
templatePath,
files[templatePath],
files,
compiledFiles
);
}
newLines.push(compiledFiles[templatePath]);
} else {
newLines.push(line);
}
});
compiledFiles[filePath] = newLines.join('\n');
}
function getHtmlFiles(dir, filelist) {
filelist = filelist || [];
fs.readdirSync(dir).forEach(file => {
const filePath = path.join(dir, file);
if (fs.statSync(filePath).isDirectory()) {
filelist = getHtmlFiles(filePath, filelist);
} else if (file.indexOf('.html') !== -1) {
filelist.push(filePath);
}
});
return filelist;
}
module.exports = dir => {
const compiledFiles = {};
const files = {};
const htmlFiles = getHtmlFiles(dir);
htmlFiles.forEach(file => {
const lines = fs.readFileSync(file, 'utf8').split('\n');
const newLines = [];
const componentPath = file.match(/^(.*[\\\/])/)[0];
lines.forEach(line => {
const js = line.match(/script.*src="(.*)"/);
const css = line.match(/link.*href="(.*\.css)"/);
if (js) {
const script = loadFile(`${componentPath}${js[1]}`);
newLines.push(
script
? `<script>(function() {\n${script}})()</script>`
: line
);
} else if (css) {
const style = loadFile(`${componentPath}${css[1]}`);
newLines.push(style ? `<style>\n${style}</style>` : line);
} else {
newLines.push(line);
}
});
files[file] = newLines.join('\n');
});
const rootFileKey = Object.keys(files).sort(
(a, b) => a.length - b.length
)[0];
const rootFile = files[rootFileKey];
createFileRecursively(rootFileKey, rootFile, files, compiledFiles);
return compiledFiles[rootFileKey];
};