-
Notifications
You must be signed in to change notification settings - Fork 0
/
postbuild.mjs
57 lines (47 loc) · 2.13 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
import fs from 'fs'
import path from 'path'
import astroConfig from './astro.config.mjs'
const PUBLIC_DIR = astroConfig.outDir || "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]
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)
console.log('filePath: ' + 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)
}
}
})
}
console.log('PRODUCTION_URL: ' + PRODUCTION_URL)
// console.log['process.env.NODE_ENV: ' + process.env.NODE_ENV]
// if (PRODUCTION_URL && process.env.NODE_ENV === 'production') {
if (PRODUCTION_URL) {
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)
}