Skip to content

Instantly share code, notes, and snippets.

@lucas-janon
Last active April 17, 2019 13:52
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 lucas-janon/8455c74aa737fbb7b579bfdbc8a0c84a to your computer and use it in GitHub Desktop.
Save lucas-janon/8455c74aa737fbb7b579bfdbc8a0c84a to your computer and use it in GitHub Desktop.
Script to format material-ui imports
#!/usr/bin/env node
const fs = require('fs')
if (!process.argv[2]) {
console.log('File path needed')
process.exit()
}
const rx = /import (.*?) from '@material-ui\/(.*?)\/(.*?)';/
const imports = {}
const file = fs.readFileSync(process.argv[2], 'utf8')
let fileByLines = file.split('\n')
fileByLines = fileByLines.filter((line) => {
const m = line.match(rx)
if (!m) return true
imports[m[2]] = imports[m[2]] ? [...imports[m[2]], m[3]] : [m[3]]
return false
})
let strs = []
Object.keys(imports).forEach((k, i) => {
const str = imports[k].reduce(
(acc, mod, index, arr) => {
let replacement
const rx = /(.*?{)(.*)(}.*)/
if (index === 0) {
const match = acc.match(rx)
replacement = `${match[1]} ${mod} ${match[3]}`
} else if (index === arr.length - 1) {
const match = acc.match(rx)
replacement = `${match[1]}${match[2]}, ${mod} ${match[3]}`
} else {
const match = acc.match(rx)
replacement = `${match[1]}${match[2]}, ${mod}${match[3]}`
}
return replacement
},
`import { } from '@material-ui/${k}';`
)
strs.push(str)
})
const lineToWrite = 3
strs.forEach((str, i) => {
fileByLines.splice(lineToWrite + i, 0, str)
})
const finalFile = fileByLines.join('\n')
fs.writeFileSync(process.argv[2], finalFile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment