Stashing this here in case I need it in the future - used this to patch build output from a vite
based Svelte project (non-svelte-kit) to be able to be deployed from a sub-directory with plain HTML serving.
Requires walkdir
and fs-extra
.
// @ts-check | |
const path = require('path'); | |
const fs = require('fs-extra'); | |
const walkdir = require('walkdir'); | |
/** | |
* @param {string} inputPath | |
* @returns {string} | |
*/ | |
const forcePosix = (inputPath) => { | |
return inputPath.split(path.sep).join(path.posix.sep); | |
}; | |
const DIST_DIR = `${__dirname}/../dist`; | |
/** | |
* Change absolute paths to relative in all dist files | |
* - Allows for nested folder deployment | |
* @TODO probably a better way to handle this... | |
*/ | |
const forceRelativePaths = async () => { | |
const DIST_DIR_ABS = forcePosix(path.resolve(DIST_DIR)); | |
const paths = walkdir.sync(DIST_DIR); | |
console.log(paths); | |
await Promise.all( | |
paths.map(async (path) => { | |
if (/\.(?:js|css|html)$/i.test(path)) { | |
let relativePrefix = './'; | |
const relativePosixPath = forcePosix(path).replace(`${DIST_DIR_ABS}/`, ''); | |
const nestedDepth = relativePosixPath.split('/').length - 1; | |
console.log({ relativePosixPath, nestedDepth }); | |
// Some tricky stuff going on with nesting in _assets | |
if (nestedDepth > 0 && relativePosixPath.startsWith('_assets') && relativePosixPath.endsWith('.css')) { | |
relativePrefix = Array(nestedDepth).fill('..').join('/') + '/'; | |
} | |
const fileContentStr = (await fs.readFile(path)).toString(); | |
// Rare - fix nested assets | |
let fixedStr = fileContentStr.replace(/(["'])(?:\.\.\/)+assets/gm, (match, c1) => { | |
return `${c1}${relativePrefix}assets`; | |
}); | |
// Typical quote wrapped absolute paths | |
fixedStr = fixedStr.replace(/(["'])\/([^.]+)/gm, (match, c1, c2) => { | |
return `${c1}${relativePrefix}${c2}`; | |
}); | |
// URL() WITHOUT quotes - e.g. `background-image: url(/assets/test.jpg) | |
fixedStr = fixedStr.replace(/(url\()\/([^.]+)/gm, (match, c1, c2) => { | |
return `${c1}${relativePrefix}${c2}`; | |
}); | |
// Write back to file | |
await fs.writeFile(path, fixedStr); | |
} | |
}) | |
); | |
}; | |
forceRelativePaths().then(() => { | |
process.exit(0); | |
}); |