Created
May 6, 2022 22:16
-
-
Save nckcol/2bc178a45b13f694b625bf90620c8f30 to your computer and use it in GitHub Desktop.
Rename js files with .jsx extension but without actual jsx into .js
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 parser = require("@babel/parser"); | |
const traverse = require("@babel/traverse").default; | |
const t = require("@babel/types"); | |
const fs = require("fs-extra"); | |
const path = require("path"); | |
function parse(content) { | |
return parser.parse(content, { | |
sourceType: "module", | |
plugins: [ | |
// enable jsx and flow syntax | |
"jsx", | |
"flow", | |
], | |
}); | |
} | |
function detectJsx(ast) { | |
let hasJsx = false; | |
traverse(ast, { | |
enter(path) { | |
if (t.isJSX(path.node)) { | |
hasJsx = true; | |
} | |
}, | |
}); | |
return hasJsx; | |
} | |
async function rename() { | |
const { globby } = await import("globby"); | |
const files = await globby("./packages/webapp/**/*.jsx"); | |
console.log(files); | |
for (const file of files) { | |
const filename = path.resolve(process.cwd(), file); | |
console.log(filename); | |
const contents = await fs.readFile(filename, "utf-8"); | |
const ast = parse(contents); | |
if (!detectJsx(ast)) { | |
const basename = path.basename(filename, path.extname(filename)); | |
await fs.rename( | |
filename, | |
path.join(path.dirname(filename), basename + ".js") | |
); | |
} | |
} | |
} | |
rename(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment