Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.