forked from klalicki/portfolio-builder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
postbuild.mjs
70 lines (64 loc) · 2.01 KB
/
postbuild.mjs
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
import fs from "fs";
import path from "path";
import astroConfig from "./astro.config.mjs";
const PUBLIC_DIR = astroConfig.dist || "dist";
const argvs = process.argv.slice(2);
if ((argvs[0] === "--p" || argvs[0] === "-path") && argvs[1]) {
let files = [];
const extensions = [".html", ".css", ".js", ".json"];
const PRODUCTION_URL = argvs[1];
console.log("production url: " + PRODUCTION_URL);
const replaceUrlsInFiles = function (dirPath, arrayOfFiles) {
files = fs.readdirSync(dirPath);
files.forEach(function (file) {
const current = fs.statSync(dirPath + "/" + file);
if (current.isDirectory()) {
replaceUrlsInFiles(dirPath + "/" + file, arrayOfFiles);
} else {
const filePath = path.join(
path.dirname(import.meta.url.replace(/file\:/, "")),
dirPath,
"/",
file
);
if (extensions.includes(path.extname(filePath))) {
let content = fs.readFileSync(filePath);
content = String(content).replace(
/src="\//g,
`src="${PRODUCTION_URL}`
);
content = String(content).replace(
/href="\//g,
`href="${PRODUCTION_URL}`
);
content = String(content).replace(
/url\("\//g,
`url("${PRODUCTION_URL}`
);
content = String(content).replace(
/src='\//g,
`src='${PRODUCTION_URL}`
);
content = String(content).replace(
/href='\//g,
`href='${PRODUCTION_URL}`
);
content = String(content).replace(
/url\('\//g,
`url('${PRODUCTION_URL}`
);
fs.writeFileSync(filePath, content);
}
}
});
};
if (PRODUCTION_URL && process.env.NODE_ENV !== "development") {
replaceUrlsInFiles(PUBLIC_DIR, files);
} else {
console.log("skip postbuild");
process.exit(0);
}
} else {
console.error('please provide a path argument "-path", "--p"');
process.exit(1);
}