Skip to content

Commit

Permalink
SP-03: Add post build
Browse files Browse the repository at this point in the history
  • Loading branch information
Tihi321 committed Mar 13, 2024
1 parent e030b17 commit 1bf5312
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
2 changes: 1 addition & 1 deletion astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import postcss from 'postcss';
export default defineConfig({
integrations: [sitemap()],
outDir: './dist',
site: 'https://tihi321.github.io/astro-start-tab/',
site: ' https://tihi321.github.io/astro-start-tab',
vite: {
plugins: [
postcss({
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"dev": "astro dev",
"start": "astro dev",
"build": "astro check && astro build",
"postbuild": "node ./postbuild.mjs -path https://tihi321.github.io/astro-start-tab",
"preview": "astro preview",
"astro": "astro"
},
Expand Down
49 changes: 49 additions & 0 deletions postbuild.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
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]


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=["'][.]{0,1}\//g, `src="${PRODUCTION_URL}`);
content = String(content).replace(/href=["'][.]{0,1}\//g, `href="${PRODUCTION_URL}`);
content = String(content).replace(/url\(["'][.]{0,1}\//g, `url("${PRODUCTION_URL}`);

fs.writeFileSync(filePath, content)
}
}
})
}

if (PRODUCTION_URL && process.env.NODE_ENV === 'production') {
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)
}

0 comments on commit 1bf5312

Please sign in to comment.