Skip to content

Instantly share code, notes, and snippets.

@nckcol
Created May 6, 2022 22:16
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 nckcol/2bc178a45b13f694b625bf90620c8f30 to your computer and use it in GitHub Desktop.
Save nckcol/2bc178a45b13f694b625bf90620c8f30 to your computer and use it in GitHub Desktop.
Rename js files with .jsx extension but without actual jsx into .js
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