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

Don’t multi-line imports (let them take less space) / Conflict with VSCode’s organizeImports #5995

Open
dimikot opened this issue Mar 20, 2019 · 121 comments · May be fixed by #13353
Open

Don’t multi-line imports (let them take less space) / Conflict with VSCode’s organizeImports #5995

dimikot opened this issue Mar 20, 2019 · 121 comments · May be fixed by #13353
Labels
lang:javascript Issues affecting JS status:needs discussion Issues needing discussion and a decision to be made before action can be taken

Comments

@dimikot
Copy link

dimikot commented Mar 20, 2019

Hi.

There is a bug somewhere when builtin VSCode's source.organizeImports feature is used together with Prettier.

People sometimes prefer to use VSCode's built-in source.organizeImports feature ON SAVE which, among other things, places all imports on the same line. And this conflicts with Prettier when it formats imports at multiple lines: if there is an error in the code, the underlining of this error shifts towards beginning of the file.

I recorded a video which shows the effect, pretty easy to reproduce:
https://www.dropbox.com/s/apj5znzlqy8pub6/vscode-prettier.mp4?dl=0

There are two possible ways I imagine:

  1. Fix the bug somehow (I tried to find the root case, but failed unfortunately), so organizeImports + Prettier could work together.
  2. Introduce an option which allows to turn off imports indentation in Prettier (a quick PR: Add option neverIndentImports to skip import statements formatting #5991) - it's a work-around in some sense, but at the same time, having all imports on the same line is VSCode's default they evangelize, and Prettier in some sense goes against this default.
@lydell
Copy link
Member

lydell commented Mar 20, 2019

Hi! Thanks for the well written issue and the video!

VSCode underlining in the wrong place sounds like a bug in VSCode and/or the Prettier VSCode plugin to me – please report this to either/both of those!

That being said, I do think it would be interesting to discuss not breaking import statements into multiple lines. I happen to have discussed this thing before, for elm-format (another code formatter): avh4/elm-format#324 (comment)

I would not mind elm-format automatically splitting long those [long import lines]!

Hmm … I might have to take that back. I worked on a view file today where the imports ended up taking a whole screen-full. So I tried joining each import to a single line. They became quite long – but it I think I like it better! I don’t really read the imports, so it was nicer to get to see the actual contents of the without scrolling a full page.

It happens quite often to me that files start with more than a window-full of just imports, that I have to scroll past every time I open them. To me it has started to feel more and more that imports are just cruft at the top of the file that I rarely look at and want to spend as little time on as possible. I want the computer to add new imports and remove unused ones, sort them and format them, and otherwise mostly keep them out of the way.

I think not breaking imports onto multiple lines could help with this. It could at least be worth exploring.

@lydell lydell added status:needs discussion Issues needing discussion and a decision to be made before action can be taken lang:javascript Issues affecting JS labels Mar 20, 2019
@lydell lydell changed the title VSCode shifts errors underlining when Perttier's multiline import formatting applies Don’t multi-line imports (let them take less space) / Conflict with VSCode’s organizeImports Mar 20, 2019
@dimikot
Copy link
Author

dimikot commented Mar 20, 2019

it has started to feel more and more that imports are just cruft at the top of the file that I rarely look at

Exactly. Noone reads them, and even during code navigation (on Cmd+Click on some identifier), VSCode jumps us into the file which contains the imported symbol definition, not to the import statement line. Many IDEs for other languages (e.g. for Java) even collapse all import statements by default.

@brodybits
Copy link
Contributor

Just to play "devil's advocate": too many imported declarations could be a sign of a module that could be split into smaller module (ideally smaller modules that are functional:)

@bakkot
Copy link
Collaborator

bakkot commented Mar 21, 2019

I think not breaking imports onto multiple lines could help with this.

That'd make me sad. Minified code will tend to have all of its imports on the same line, even though that isn't how people normally write code, and it would be a shame for prettier to leave it in this unusual state.

Exactly. Noone reads them

This does not match my experience.

@dimikot
Copy link
Author

dimikot commented Mar 21, 2019

Minified code will tend to have all of its imports on the same line

Just to be clear, noone proposes to have all imports on the same line. The proposal is to (optionally) have symbols related to every single “import” statement on the same line, i.e. one line per each “import” statement.

@bakkot
Copy link
Collaborator

bakkot commented Mar 21, 2019

Oh! Forgive me, I misunderstood. That seems fine to me. (Doing it unconditionally, anyway; I don't think it would be worth adding an option.)

@dimikot
Copy link
Author

dimikot commented Mar 21, 2019

If we do it unconditionally, many people (the ones who got used to the current behavior) will likely be upset...

@lydell
Copy link
Member

lydell commented Mar 21, 2019

Sorry for being unclear. I meant that this:

import huffman from "n-ary-huffman";
import { repr } from "tiny-decoders";

import iconsChecksum from "../icons/checksum";
import type {
  ElementReport,
  ElementTypes,
  ElementWithHint,
  ExtendedElementReport,
  HintMeasurements,
  HintUpdate,
} from "../shared/hints";
import {
  type HintsMode,
  type KeyboardAction,
  type NormalizedKeypress,
} from "../shared/keyboard";
import {
  Resets,
  addListener,
  bind,
  isMixedCase,
  log,
  makeRandomToken,
  partition,
  splitEnteredText,
  unreachable,
} from "../shared/main";
import type {
  FromBackground,
  FromOptions,
  FromPopup,
  FromRenderer,
  FromWorker,
  ToBackground,
  ToOptions,
  ToPopup,
  ToRenderer,
  ToWorker,
} from "../shared/messages";
import {
  type OptionsData,
  type PartialOptions,
  flattenOptions,
  getDefaults,
  makeOptionsDecoder,
  unflattenOptions,
} from "../shared/options";
import { type Durations, type Perf, TimeTracker } from "../shared/perf";

Would be printed as:

import huffman from "n-ary-huffman";
import { repr } from "tiny-decoders";

import iconsChecksum from "../icons/checksum";
import type { ElementReport, ElementTypes, ElementWithHint, ExtendedElementReport, HintMeasurements, HintUpdate } from "../shared/hints";
import { type HintsMode, type KeyboardAction, type NormalizedKeypress } from "../shared/keyboard";
import { Resets, addListener, bind, isMixedCase, log, makeRandomToken, partition, splitEnteredText, unreachable } from "../shared/main";
import type { FromBackground, FromOptions, FromPopup, FromRenderer, FromWorker, ToBackground, ToOptions, ToPopup, ToRenderer, ToWorker } from "../shared/messages";
import { type OptionsData, type PartialOptions, flattenOptions, getDefaults, makeOptionsDecoder, unflattenOptions } from "../shared/options";
import { type Durations, type Perf, TimeTracker } from "../shared/perf";

And most likely behind an option, yes.

@alfnielsen
Copy link

alfnielsen commented Mar 28, 2019

Hi,
In my team we want to use Prettier so we avoid the generel discussion on format,
but import statement over multiple line is an absolute no-go.

There are a couple of reasons for this:

  • Most important for me is, that no person should write imports at all, the formatter/vscode/prettier should do this so we avoid different versions and possible merge conflict, and as described in Prettier's "Option Philosophy" its about avoiding individuals opinions on format.

  • But it is a real bug that Prettier convert imports to multiline because of //@ts-ignore which we are forced to used for some js modules in our typescript code.

What you should be able to write is:

//@ts-ignore
import { a, b } from 'MyNonTypedModule'

But it's converted to:

//@ts-ignore
import { 
  a, 
  b 
} from 'MyNonTypedModule'

And this fails.

We can fix this by writing:

import { 
 a, 
 b
//@ts-ignore
 } from 'MyNonTypedModule'

But now auto import stop working.
If I import a new part from 'MyNonTypedModule' let say 'c',
it will be added as a new import statement

import { 
 a, 
 b
//@ts-ignore
 } from 'MyNonTypedModule'
import { c }  from 'MyNonTypedModule'

I hope we all can agree that this is a real bug, not just a personal opinion on formatting code?

(And maybe I should have written it is its own issue, but: )

I have written an option 'ForceSingleLineImports' with full tests,
default value false (So it dont change anything for anybody unless they activate it)
that do exactly what @lydell suggesting, and this fixes all my and my teams problems.

Im new to opensource projects on github, so I dont know how to get the code up.
(I cloned the project, made the changes and the tests, in it's own branch, but I dont have permission to upload the branch)

Can anyone help me with the permission?
Then you can see the code,
or write back why you dont think this should be in Prettier :)

@j-f1
Copy link
Member

j-f1 commented Mar 28, 2019

We probably won’t add an option for this, but I recommend:

  • opening a bug report in the VS Code repo (if there isn’t one already) about the comment issue
  • forking this repo (https://github.com/prettier/prettier/fork) so you can publish your branch for others to use

I’d also encourage you to use your forked version — we’re perfectly fine with that if you can’t use the official version of Prettier.

Finally, have you considered authoring types for the non-typed modules you have? It would fix your whole problem.

@alfnielsen
Copy link

Hi @j-f1
Thank for the answer.
We dont really have the resources for fixing(adding types) and following changes for a lot of non-typed modules, so I dont believe that is a good ideer.
(Some of the modules are actually written in typescript, but they dont use NoImplicitAny, which gives the same problem - we need ts-ignore or remove no-implicit-any, and that, my opinion, removes one the main reason for using ts in the first place.)
Im also a little concerned about the force, for the same reason. (Then I need to following all fixes you make and making parallel updates (re-forking) to my forked version, unless there is some smart way that im not aware of?)
But I will report it on VS Code as you suggest and talk with my team about holding a Prettier fork updated.

@duailibe
Copy link
Member

duailibe commented Apr 1, 2019

many people (the ones who got used to the current behavior) will likely be upset

Yes. We've had requests for doing the opposite, i.e. always break named imports in multiple lines. And also had #1954

@lydell
Copy link
Member

lydell commented Apr 1, 2019

Playing Devil's advocate: The rational thing to do for people like me, who think the imports take too much space, would be to put all imports at the end of the file.

@j-f1
Copy link
Member

j-f1 commented Apr 2, 2019

That’s actually a good idea @lydell!

@galkin
Copy link

galkin commented Apr 26, 2019

Any updated about this?

@positlabs
Copy link

We probably won’t add an option for this

@j-f1 What's the reasoning behind not supporting the single-line format for imports?

@csvn
Copy link

csvn commented May 10, 2019

We probably won’t add an option for this

That's a shame. Not keeping imports on one line to me is a blocker from ever using Prettier (and not a fork). I mostly use Typescript, and it often has additional imports (for typing) that makes multi-line imports occur more often.

Adding 5-20 lines for a large percentage of files is just more noise, as I don't feel like imports need to be viewed very often (linting warns for unused imports, editors will often auto import functions/classes). This feels like the return of code folding for imports, where e.g. Java in Webstorm automatically hides imports to keep code readable.

@alfnielsen
Copy link

Hi
I have written an extension to vscode called vsc-organize-imports, that work with prettier.
It can be set up to FormatOnSave, which will run after Prettier,
and format the imports to single lines or multi-lines depending on settings.

I have written it, because it's for me, is important that the imports are sorted and single line,
but I added the option for those people that wants multi-line version,
so maybe some of the people writing on this issue will find it useful.

@phaux
Copy link

phaux commented May 27, 2019

How about formatting them like this:

import {
  Lorem, ipsum, dolor, sit, amet, consectetur, adipiscing, elit,
  Maecenas, vitae, venenatis, arcu, Sed, ultrices,
} from "lorem-ipsum"

@lffg
Copy link

lffg commented Sep 9, 2019

Anything new here?


Why a new option can't be created? This behavior is very noisy sometimes, especially in TypeScript files, which requires a lot of type importing (which usually have long names).

Because of that I get this output:

import { compare } from 'bcryptjs';
import { sign, verify } from 'jsonwebtoken';
import { getManager } from 'typeorm';
import {
  AUTH_REFRESH_TOKEN_KEY as REFRESH_TOKEN_KEY,
  AUTH_ACCESS_TOKEN_KEY as ACCESS_TOKEN_KEY
} from '../constants/env';
import {
  AUTH_INVALID_CREDENTIALS as INVALID_CREDENTIALS,
  AUTH_INVALID_TOKEN as INVALID_TOKEN
} from '../constants/error-codes';
import User from '../entities/User';
import { RefreshJwtToken, AccessJwtToken } from '../types/Tokens';
import AuthorizationError from '../utils/errors/AuthorizationError';

A good portion of the JavaScript (and TypeScript) community also consider this format uglier, and not prettier. (Please don't take this too serious lol)

I know that a new option can't be created for every single code-style aspect, but I really think that this one is very important for some use cases, such as this one.

Please consider adding this option! :)

@lydell
Copy link
Member

lydell commented Sep 10, 2019

Why a new option can't be created?

Please see our Option Philosophy.

@legalbrickstechnology-dcm
Copy link

legalbrickstechnology-dcm commented Oct 8, 2019

Please consider a way around this... it really is frustrating when you cant see the top line of your component when you open a file because of it being multi-lined. I want this functionality everywhere except my imports :(

import {
  AfterViewInit,
  Component,
  ComponentFactoryResolver,
  EventEmitter,
  Injector,
  Input,
  Output,
  Type,
  ViewChildren,
  ViewContainerRef
} from '@angular/core';

@vedmant
Copy link

vedmant commented Nov 22, 2019

I also find this very uncomfortable to break imports to multiple lines, the imports part of the file gets too large and I need to scroll over it every time I open the file, plus it looks not consistent when one imports are written in one line while another it multiple, for me it's much simpler to scroll horizontally (on MacOs) and keep it in long line, I rarely need to look what's in my imports. This one of the reasons why I'm considering not using prettier.

@phaux
Copy link

phaux commented Nov 23, 2019

I would find it very valuable to match the behavior of typescript's organize imports command. Right now they're kinda fighting each other. Both typescript and prettier are very widespread amongst the projects I've been working with.

@TotomInc
Copy link

2023 +1 ?

@pepew-le-boss
Copy link

Is there a prettier plugin that can fix this problem ? (I was not able to find one)

@DustInComp
Copy link

Putting // prettier-ignore before long import lines until I find a replacement.

@jonlepage
Copy link

yes, use eslint

@Trystan-SA
Copy link

The horror on my face seeing there is STILL no option for this crap...

@RonRofe
Copy link

RonRofe commented Apr 19, 2023

Lets create a "democraticPrettier", release it to the public and kill prettier!

@biton-ron
Copy link

It feels like you were never forced to work on a large TypeScript project, requiring the entire first view of the file to be a mass bulk of imports 90% of which are types. Makes us rethink using Prettier as a whole. This thread and answers from your team is outrages.

@ReallyVirtual
Copy link

Lets create a "democraticPrettier", release it to the public and kill prettier!

'prettiest'?

@tgangso
Copy link

tgangso commented Apr 27, 2023

Where is the option to configure this already?

@ReeseLiu2021
Copy link

2023 +1

@dinbtechit
Copy link

We need this option so badly. the imports look so messy!!!! Each import statements take 15 lines. eww.
++++++++ 1

@jamelt
Copy link
Contributor

jamelt commented Jun 6, 2023

Take a look at dprint - https://github.com/dprint/dprint. You could probably get it configured to function mostly like prettier. There is an option for single-line imports.

@lintonpereira
Copy link

Please, implement this option!!

@StinsonZhao
Copy link

2023, prettier 3.0, nothing changed for this?

@am-maneaters
Copy link

am-maneaters commented Jul 12, 2023

since it doesn't seem like there's much traction on this issue. the bare minimum i would recommend is using the editor.foldingImportsByDefault setting in VSCode. it does not solve the issue of imports being multiple lines long but it does at least hide the import hell at the top of your files

@hesperius1
Copy link

Our org was trying to incorporate prettier, but this import hell is just a nonsense. This decision is a very questionable (at least) and response is lacking any meaningful reasons to support the decision, and rather looks quite personal. This is just a disappointment.

@sillvva
Copy link

sillvva commented Aug 24, 2023

4 years... no change

SkySails added a commit to Navigraph/msfs-navigation-data-interface that referenced this issue Oct 27, 2023
**Note**: Yes, the imports being on multiple lines is really annoying.

No, unfortunately there is no way around this currently :(
prettier/prettier#5995
SkySails added a commit to Navigraph/msfs-navigation-data-interface that referenced this issue Nov 27, 2023
**Note**: Yes, the imports being on multiple lines is really annoying.

No, unfortunately there is no way around this currently :(
prettier/prettier#5995
SkySails added a commit to Navigraph/msfs-navigation-data-interface that referenced this issue Nov 27, 2023
**Note**: Yes, the imports being on multiple lines is really annoying.

No, unfortunately there is no way around this currently :(
prettier/prettier#5995
@nekochan0122
Copy link

Try out ESLint Stylistic
https://eslint.style/

image

@John-Dennehy
Copy link

Are Prettier devs seriously ignoring the demand for this feature for more than 4 years?? Wow. Really makes me want to look into alternatives. 😒

@dinbtechit
Copy link

In all fairness, this is an open-source project, so we can't expect much. But we migrated to ESLint and loved it so far.

@akdasa
Copy link

akdasa commented Jan 16, 2024

Shame on you guys...

@stereokai
Copy link

Prettier devs - this is inexcusable, causing a lot of headaches and costing a lot of man hours only due to your stubbornness!

@John-Dennehy
Copy link

John-Dennehy commented Mar 5, 2024

I switched to Biome.js due to this a few months back. Been very impressed. While there will never be an opinionated formatter that everyone can agree 100% with, and don't agree with all of the decisions made by Biome.js, they have done a much better job of articulating the technical reasons behind the choices, so it never feels arbitrary or just down to a personal preference.

@Philix27
Copy link

Philix27 commented Mar 21, 2024

Still no solution

@stereokai
Copy link

I wrote a VSCode extension that overrides Prettier's default import formatting, irregardless of any printWidth setting: Run commands as code actions

You will need to use it together with this extension JS/TS Import/Export Sorter

The following configuration will enforce single-line imports yet allow Prettier to format everything else.

  "editor.formatOnSave": false,
  "editor.codeActionsOnSave": [
    "source.organizeImports", // Optional
    "source.runCommandsAsCodeActions.formatAndSave"
  ],
  "run-commands-as-code-actions.formatAndSave": [{
    "command": "prettier.forceFormatDocument",
    "delay": 0
  }, {
    "command": "tsImportSorter.command.sortImports",
    "delay": 400 // Shorter might also work, but this is safe
  }, {
    "command": "workbench.action.files.saveWithoutFormatting",
    "delay": 400 // Shorter might also work, but this is safe
  }],
  "tsImportSorter.configuration.emptyLinesBetweenGroups": 0,
  "tsImportSorter.configuration.excludeGlob": ["**/node_modules/**"], // Adjust to your liking
  "tsImportSorter.configuration.maxLineLength": 0,
  "tsImportSorter.configuration.wrappingStyle": {
    "ignoreComments": false, // Optional
    "maxBindingNamesPerLine": 0,
    "maxDefaultAndBindingNamesPerLine": 0,
    "maxExportNamesPerLine": 0,
    "maxNamesPerWrappedLine": 0
  },

@dot-ottor
Copy link

I switched to Biome.js due to this a few months back. Been very impressed. While there will never be an opinionated formatter that everyone can agree 100% with, and don't agree with all of the decisions made by Biome.js, they have done a much better job of articulating the technical reasons behind the choices, so it never feels arbitrary or just down to a personal preference.

@John-Dennehy are you willing to share your biome config that does this (non multi line imports)? Also running into this issue at work and the biome docs don't really explain it well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
lang:javascript Issues affecting JS status:needs discussion Issues needing discussion and a decision to be made before action can be taken
Projects
None yet
Development

Successfully merging a pull request may close this issue.