-
Notifications
You must be signed in to change notification settings - Fork 5
/
inject_base.cjs
52 lines (45 loc) · 1.49 KB
/
inject_base.cjs
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
const fs = require('fs');
const path = require('path');
const { traverse, slash } = require('./lib.cjs');
function inject_base(pages) {
// get all page's index.html
const pageIndexes = traverse(pages).filter((file) => file.name === 'index.html');
for (const page of pageIndexes) {
const indexHTMLPath = path.join(pages, page.relativePath);
let indexHTMLContent = fs.readFileSync(indexHTMLPath).toString();
const pageIndexHTMLURLPath = slash(page.relativePath);
const pageURLPath = path.dirname(pageIndexHTMLURLPath);
let numSegment = 0;
let baseHref = '.';
if (pageURLPath != '' && pageURLPath != '.' && pageURLPath != './') {
const numSlashes = pageURLPath.split('/').length - 1;
numSegment++;
baseHref = '..';
for (let i = 0; i < numSlashes; i++) {
baseHref += '/..';
numSegment++;
}
}
// inject the dynamic base
const windowBaseScript = `
<script>
window.BASE = location.pathname.split('/').slice(0, -"${baseHref}".split('..').length).join('/');
</script>
`;
const firstScript = indexHTMLContent.indexOf('<script');
const headEnd = indexHTMLContent.indexOf('</head');
const insertion = firstScript > -1 && headEnd < firstScript ? headEnd : firstScript;
indexHTMLContent =
indexHTMLContent.slice(0, insertion) +
`${windowBaseScript}` +
indexHTMLContent.slice(insertion);
fs.writeFileSync(indexHTMLPath, indexHTMLContent);
}
}
module.exports = {
inject_base
};
if (require.main === module) {
// TODO: argument
inject_base('build');
}