Skip to content

Instantly share code, notes, and snippets.

@aemaem
Created March 20, 2019 12:38
Show Gist options
  • Save aemaem/886520689e012f027f2793ef641f841d to your computer and use it in GitHub Desktop.
Save aemaem/886520689e012f027f2793ef641f841d to your computer and use it in GitHub Desktop.
Next.js post export script to change url file paths to relative ones
const fs = require('fs');
const proc = require('process');
const path = require('path');
function modifyUrl(content, depth) {
let replacementArray = [];
for (let i = 0; i < depth; i++) {
replacementArray.push('..');
}
let replacement = replacementArray.join('/');
if (replacementArray.length > 0) {
replacement = `${replacement}/`;
}
return content.replace(/url\("\//gm, `url("${replacement}`)
.replace(/url\('\//gm, `url('${replacement}`)
.replace(/url\(\//gm, `url(${replacement}`)
}
function convertToRelativeFilePaths(directory, depth = 0, extensionRegex = /^\.css$/) {
fs.readdir(directory, (error, files) => {
if (error) {
console.error(`Unable to list directory ${directory}`, error);
proc.exit(1)
}
files.forEach((file, index) => {
let absolutePath = path.join(directory, file);
fs.stat(absolutePath, (error, stat) => {
if (error) {
console.error(`Unable to stat path ${absolutePath}`, error);
return
}
if (stat.isFile()) {
let extension = path.extname(absolutePath);
if (!extensionRegex.test(extension)) {
return
}
console.debug(`Processing file ${absolutePath}`);
fs.readFile(absolutePath, 'utf8', (error, data) => {
if (error) {
console.error(`Unable to read file ${absolutePath}`, error);
return
}
let result = modifyUrl(data, depth);
fs.writeFile(absolutePath, result, error => {
if (error) {
console.error(error)
}
});
});
} else if (stat.isDirectory()) {
convertToRelativeFilePaths(absolutePath, depth + 1)
} else {
console.warn(`Unknown file stat for ${absolutePath}`)
}
});
});
});
}
// call like `node relativateCssUrls.js out`
convertToRelativeFilePaths(proc.argv[2]);
@aemaem
Copy link
Author

aemaem commented Mar 20, 2019

This is needed because I am tired of spending hours and days on JS/TS project setups.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment