IanVS / prettier-plugin-sort-imports

An opinionated but flexible prettier plugin to sort import statements
Apache License 2.0
951 stars 21 forks source link

Multiple inline-style type imports from the same file adds a side-effect import for the same file #124

Closed AlexJDG closed 11 months ago

AlexJDG commented 11 months ago

Your Environment

Describe the bug

When running prettier on a file that has multiple inline type imports from the same file:

import { type x, type y } from "./myFile";

the plugin will add another side-effect import for the same file:

import "myFile";
import type { x, y } from "./myFile";

To Reproduce

// typeImportTest.types.ts
export type TFirstTest = "first";
export type TSecondTest = "second";
export type TThirdTest = "third";
// typeImportTest.ts
import { type TFirstTest, type TSecondTest } from "./typeImportTest.types";

const first: TFirstTest = "first";
const second: TSecondTest = "second";

Run prettier -w typeImportTest.ts

Expected behaviour

File should remain unchanged.

Actual behaviour

import "./typeImportTest.types";
import type { TFirstTest, TSecondTest } from "./typeImportTest.types";

const first: TFirstTest = "first";
const second: TSecondTest = "second";

Configuration File (.prettierrc.js)

module.exports = {
    singleAttributePerLine: true,
    tabWidth: 4,
    plugins: ["@ianvs/prettier-plugin-sort-imports"],
    importOrderTypeScriptVersion: "^4.9.3",
    importOrder: [
        "<TYPES>",
    ],
};

Additional thoughts

It looks like the plugin is attempting to find non-type imports in the destructuring-style import and break them out into a separate line, since if you import a variable from the file as well:

import { type TFirstTest, type TSecondTest, variable } from "./typeImportTest.types";

then the resulting output is valid:

import { variable } from "./typeImportTest.types";
import type { TFirstTest, TSecondTest } from "./typeImportTest.types";

So it looks like the fix would be to check whether there are any non-type imports extracted from the import group before appending another import.

AlexJDG commented 11 months ago

Opened a PR for this here: https://github.com/IanVS/prettier-plugin-sort-imports/pull/125