Last active
May 11, 2018 05:41
-
-
Save Pro542/0f7a200dfc3e566af855637f2c77e88b to your computer and use it in GitHub Desktop.
Change code in directory to typescript
This file contains hidden or 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
// this script is used to: | |
// - rename .js files to .tsx and .ts | |
// - remove "// @flow" from top of files | |
// script is unsafe | |
// run from root of project | |
const fs = require('fs'); | |
const path = require('path'); | |
const dirPath = 'components'; | |
/** | |
* Find all files inside a dir, recursively. | |
* @function getAllFiles | |
* @param {string} dir Dir path string. | |
* @return {string[]} Array with all file names that are inside the directory. | |
* from https://gist.github.com/kethinov/6658166 | |
*/ | |
const getAllFiles = dir => | |
fs.readdirSync(dir).reduce((files, file) => { | |
const name = path.join(dir, file); | |
const isDirectory = fs.statSync(name).isDirectory(); | |
const isJs = path.extname(file) === '.js'; | |
if (isDirectory) { | |
return [...files, ...getAllFiles(name)] | |
} else if (isJs) { | |
return [...files, name]; | |
} else { | |
return [...files]; | |
} | |
}, []); | |
let fileCount = 0; | |
//iterates through each file in the components directory with .js extension | |
getAllFiles(dirPath).forEach((file) => { | |
console.log(`Processing file ${file}`); | |
// If filename has Styles.js at the end, rename it (not checked for "// @flow") | |
if (/Styles\.js$/.test(file) || /^index\.js$/.test(file)) { | |
fs.renameSync(file, file.replace(/\.js$/, '.ts')); | |
console.log(`${file}\t=>\t${file.replace(/.js$/, '.ts')}`); | |
} else { | |
console.log(file); | |
let fileContent = fs.readFileSync(file, 'utf8'); | |
if (/^\/\/ @flow\n/.test(fileContent)) { | |
const newFileContent = fileContent.substr(fileContent.indexOf('\n') + 1); | |
fs.writeFileSync(file, newFileContent); | |
console.log('\tRemoved first line from file'); | |
fileContent = fs.readFileSync(file, 'utf8'); | |
} | |
if (/Styles\.js'/.test(fileContent)) { | |
const newFileContent = fileContent.replace(/Styles\.js'/, 'Styles\''); | |
fs.writeFileSync(file, newFileContent); | |
console.log('\tRemoved .js from import'); | |
fileContent = fs.readFileSync(file, 'utf8'); | |
} | |
// (file is not explicitly checked if it has JSX) | |
fs.renameSync(file, file.replace(/\.js$/, '.tsx')); | |
console.log(`${file}\t=>\t${file.replace(/.js$/, '.tsx')}`); | |
} | |
fileCount++; | |
}); | |
console.log('.js files read: ', fileCount); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment