Created
March 20, 2019 12:38
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is needed because I am tired of spending hours and days on JS/TS project setups.