Last active
April 22, 2019 14:26
-
-
Save andr3medeiros/4faef40e2c0a714011dd2a50fb562e88 to your computer and use it in GitHub Desktop.
Transform full lodash imports into imports for separated modules
This file contains 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 glob = require('glob'); | |
const fs = require('fs'); | |
// Find file(s) | |
glob('*/**/*.+(js|jsx)', (err, files) => { | |
if (err) { throw err; } | |
console.log(`Found ${files.length} files to check...`); | |
files.forEach(item => { | |
// Read file | |
const content = fs.readFileSync(item, 'utf8'); | |
let newContent = content; | |
const requireRegex = /const\s*_\s*=\s*require\(['"]lodash['"]\);*\n/gi; | |
const required = content.match(requireRegex); | |
const oneLinerRegex = /import\s*\{[(\w),\s]+\}\s*from\s*['"]lodash['"];*\n/gi; | |
const oneLiner = content.match(oneLinerRegex); | |
const importAllRegex = /import\s*_\s*from\s*['"]lodash['"];*\n/gi; | |
const allImported = content.match(importAllRegex); | |
if (!allImported && !oneLiner && !required) return; | |
if (oneLiner) { | |
let main = oneLiner[0].replace(/import\s*\{/, ''); | |
main = main.replace(/\}\s*from\s*['"]lodash[/'"]\w*;*/, ''); | |
const matches = main.match(/\w+/gi); | |
matches.forEach(match => { | |
newContent = `import ${match} from 'lodash/${match}';\n${newContent}`; | |
}); | |
newContent = newContent.replace(oneLinerRegex, ''); | |
} | |
const underscoreMatches = content.match(/_\.\w+/gi); | |
if ((allImported || required) && underscoreMatches && underscoreMatches.length) { | |
const repeatedMatches = []; | |
underscoreMatches.forEach(dirtyMatch => { | |
const match = dirtyMatch.replace('_.', ''); | |
if (repeatedMatches.some(repeatedMatch => repeatedMatch === match)) return; | |
repeatedMatches.push(match); | |
newContent = `import ${match} from 'lodash/${match}';\n${newContent}`; | |
}); | |
underscoreMatches.forEach(dirtyMatch => { | |
const match = dirtyMatch.replace('_.', ''); | |
newContent = newContent.replace(dirtyMatch, match); | |
}); | |
} | |
newContent = newContent.replace(importAllRegex, ''); | |
newContent = newContent.replace(requireRegex, ''); | |
console.log(item + ' changed'); | |
fs.writeFile(item, newContent, 'utf8', writeFileError => console.error(writeFileError)); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment