jscodeshift
jscodeshift copied to clipboard
Double semicolons in interface after insert
This can be reproduced using https://astexplorer.net/ and the sample code below. This is my first time using jscodeshift
, so I may be holding something wrong. If I strip out all the semicolons from the source, then oddly it works and inserts only a single semicolon for all them.
example.ts
export interface Test {
A: string;
D: string;
F: string;
R: string;
X: string;
}
transformer.js
// jscodeshift can take a parser, like "babel", "babylon", "flow", "ts", or "tsx"
// Read more: https://github.com/facebook/jscodeshift#parser
export const parser = "tsx";
const nameToAdd = "O";
// Press ctrl+space for code completion
export default function transformer(file, api) {
const j = api.jscodeshift;
const root = j(file.source);
let hasAdded = false;
const names = root
.find(j.TSInterfaceDeclaration, { id: { name: "Test" } })
.find(j.TSPropertySignature)
.find(j.Identifier);
names.forEach((path, i) => {
if (path.value.name === nameToAdd) {
hasAdded = true;
}
if (hasAdded) {
return;
}
if (path.value.name.localeCompare(nameToAdd) > 0) {
hasAdded = true;
path.parentPath.insertBefore(`${nameToAdd}: string`);
} else if (i + 1 === names.length) {
hasAdded = true;
path.parentPath.insertAfter(`${nameToAdd}: string`);
}
});
return root.toSource();
}
Output
export interface Test {
A: string;;
D: string;;
F: string;;
O: string;
R: string;;
X: string;;
}