facebook / jscodeshift

A JavaScript codemod toolkit.
https://jscodeshift.com
MIT License
9.11k stars 468 forks source link

how to remove empty line using jscodeshift? #578

Closed sibelius closed 4 weeks ago

sibelius commented 7 months ago

I want to transform this

const obj = {
  a: 'a',

  b: 'b',

  c: 'c',
  d: 'd',
}

into this

const obj = {
  a: 'a',
  b: 'b',
  c: 'c',
  d: 'd',
}

this is my first approach

import type { API, FileInfo, Options } from 'jscodeshift';

import { getPrintOptions } from '../getPrintOptions';

function transform(file: FileInfo, api: API, options: Options) {
  const j = api.jscodeshift; // alias the jscodeshift API

  const root = j(file.source); // parse JS code into an AST

  const printOptions = getPrintOptions(options);

  let linesToRemove = [];

  root
    .find(j.ObjectExpression)
    .forEach((path) => {
      // Find properties in the object
      const properties = path.node.properties;

      // // Sort properties by their starting line number
      const sortedProperties = properties.sort((a, b) => a.loc.start.line - b.loc.start.line);

      // Remove any blank lines between properties
      for (let i = 0; i < sortedProperties.length - 1; i++) {
        const endLine = sortedProperties[i].loc.end.line;
        const nextStartLine = sortedProperties[i + 1].loc.start.line;

        // Remove empty lines between properties
        if (nextStartLine - endLine >= 1) {
          for (let line = endLine + 1; line < nextStartLine; line++) {
            linesToRemove = [
              ...linesToRemove,
              line,
            ];

            console.log({
              line,
            });
          }
        }
      }

      return path.node;
    });

  // linesToRemove.sort((a, b) => b - a).map((line) => {
  //   root.find(j.Literal).at(line).remove();
    // root.find(j.Identifier).at(line).remove();

    // root.find(j.Literal, { loc: { start: { line } } }).remove();
  // });

  return root.toSource(printOptions);
}

module.exports = transform;
module.exports.parser = 'tsx';
ElonVolo commented 7 months ago

I believe that anything involving spacing is going to be taking place at the recast layer as opposed to the jscodeshift layer, so it's kind of out of our hands.

You'd probably get the most mileage out of creating lint/prettier rules for your codebase and running the transformed code through that, which is what I understand what Meta does when they use jscodeshift.