Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Text in strings gets mistaken as an import statement and is removed #7

Closed
blutorange opened this issue Apr 18, 2022 · 1 comment
Closed
Assignees

Comments

@blutorange
Copy link
Collaborator

blutorange commented Apr 18, 2022

The plugin reeds to remove import statements before adding them again in the sorted order. Currently, this removal is done via a regexp https://github.com/IanVS/prettier-plugin-sort-imports/blob/main/src/utils/remove-nodes-from-original-code.ts#L37-L39

While that may be working for most cases, it is fundamentally broken and leads to cases such as

const exampleCode = `

import "./some-import";

`;

import "./some-import";

getting formatted as

import "./some-import";

const exampleCode = `


`;

import "./some-import";

We already know the start and end position of each node in the code. So we could collect the ranges [start, end][] of nodes to remove, sort by start position in reverse order (merging overlapping ranges), then delete each range from the code.

@blutorange blutorange assigned IanVS and blutorange and unassigned IanVS Apr 18, 2022
@blutorange
Copy link
Collaborator Author

blutorange commented Apr 18, 2022

And since the regex only checks for imports at the beginning of a line (which is not required by the spec), this code

/* foo */ import { foo } from "c";

import { bar } from "a";

function baz() {
}

also results in getting "formatted" as

/* foo */
import { bar } from "a";
import { foo } from "c";

import { foo } from "c";

function baz() {}

blutorange added a commit that referenced this issue Apr 18, 2022
Previously, a regex string replacement was used, and regex is an inadequate
tool for transforming entire JavaScript code files. Instead, this commit
changes that to a proper algorithm that removes the code at the source position
ranges of the nodes to be removed. This will not work properly if the Babel
parser ever did not return the correct source positions, but that is not a
regression since the former algortihm already relied on the positions
being correct.
@IanVS IanVS closed this as completed in b5c23c7 Apr 27, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants