Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Globally replace mass-lodash imports
const { exec } = require("child_process");
const fs = require("fs");
const script = exec(
"grep -lir --exclude-dir={android,ios,node_modules,coverage} \"import _ from 'lodash'\" . | grep -v .map"
);
let filesToUpdate;
const fixNextFile = () => {
if (filesToUpdate.length) {
const filename = filesToUpdate.shift();
let fileContents = fs.readFileSync(filename, {
encoding: "utf8"
});
let lodashRegex = /(_\.)([a-zA-Z]+)/g;
let lodashFns = [];
match = lodashRegex.exec(fileContents);
while (match != null) {
const wholeRef = match[0];
fileContents = fileContents.replace(wholeRef, wholeRef.substr(2));
lodashFns.push(match[2]);
match = lodashRegex.exec(fileContents);
}
lodashFns = lodashFns.filter(
(item, pos) => lodashFns.indexOf(item) === pos
);
if (lodashFns.length) {
fileContents = fileContents.replace(
"import _ from 'lodash'",
`import { ${lodashFns.join(",")} } from 'lodash'`
);
console.log(`Analysis of ${filename}`);
console.log(`Lodash functions detected: ${lodashFns.join(",")}`);
console.log("-----");
fs.writeFileSync(filename, fileContents, { encoding: "utf-8" });
} else {
console.log('Could not find lodash usage.')
}
fixNextFile();
}
};
script.stdout.on("data", function(data) {
filesToUpdate = data
.split("\n")
.filter(val => !!val)
.filter(val => !val.includes("lodash-fix"));
fixNextFile();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment