Skip to content

Instantly share code, notes, and snippets.

@moshfiqrony
Created February 21, 2023 06:12
Show Gist options
  • Save moshfiqrony/a5d363341b3eaef1c0177e2bd048a705 to your computer and use it in GitHub Desktop.
Save moshfiqrony/a5d363341b3eaef1c0177e2bd048a705 to your computer and use it in GitHub Desktop.
This code converts any px value in the js of given directory and it's sub-directories file to rem value.
const fs = require("fs");
const path = require("path");
const directoryPath = "src";
const rootFontSize = 16;
function convertFilesInDirectory(directoryPath) {
const files = fs.readdirSync(directoryPath);
for (const file of files) {
const filePath = path.join(directoryPath, file);
if (fs.statSync(filePath).isDirectory()) {
convertFilesInDirectory(filePath); // recursively process subdirectories
} else if (path.extname(file) === ".js") {
// only process javascript files
const data = fs.readFileSync(filePath, "utf8");
const newData = data.replace(/(\d*\.?\d+)px/g, (match, value) => {
const remValue = (parseFloat(value) / rootFontSize).toFixed(4);
// 1000 means we want 3 digit after decimal point
return `${Math.round(remValue * 1000) / 1000}rem`;
});
// Write into the file
fs.writeFileSync(filePath, newData, "utf8");
console.log(`Converted ${file} to use rem units`);
}
}
}
convertFilesInDirectory(directoryPath);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment