Skip to content

Instantly share code, notes, and snippets.

@Meandmybadself
Created September 4, 2019 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Meandmybadself/8694cf9cb8ccac0b70c68da2365b905d to your computer and use it in GitHub Desktop.
Save Meandmybadself/8694cf9cb8ccac0b70c68da2365b905d to your computer and use it in GitHub Desktop.
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