Closed cpcallen closed 3 months ago
Just realised that it preserves groupings of import
s where separated by blank lines. Seems like a useful feature, but we seem to have some pretty arbitrary and I think in cases quite accidental such groupings, which should probably be rectified.
(This explains why my spot-checking of side-effect-only imports suggested they were left alone: they happened to be in a separate group that was already sorted.)
Converting to draft temporarily while I rectify that.
The basics
The details
Proposed Changes
Use the
prettier-plugin-organize-imports
npm package to automatically sort imports (and remove unused imports) when formatting code using Prettier.Reason for Changes
The style guide does not give any definitive instructions about how to organise imports (unlike with
goog.requires
, for which it previously did).As a result, our
imports
have gotten to be somewhat arbitrarily ordered. This shouldn't matter, but it has a few possible consequences:import
s should not matter (order of execution of imported modules is arbitrary, so long as all are executed before the importing module) but side effects, Closure Compiler, etc. can all result in practice not strictly agreeing with theory.For those reasons I think it would be good to automatically order
import
s and do so in a way consistent with google3, and:organiseImports
API, andprettier-plugin-organize-imports
plugin also uses that same API, has no other dependencies, and is easy to set up.I am not certain that the plugin sorts in the same order as our internal tooling, because I've not been able to find documentation about the expected order for either, but the API does not seem to have much in the way of options (just an option not to remove unused imports) and some manual spot-checking did not unearth any differences. For the same reason it should also be compatible with how e.g. VSCode's organise imports functionality works too.
Additional Information
Observationally, the sort order used by the plugin is to sort by imported path:
../
before paths starting with./
.import type
before plainimport
, if both exist for the same path.Named imports are sorted alphabetically, case-insensitive.
Side-effect-only imports (
import './path/to/file.js';
) appear to be left alone at the top of the import block.