Make Prettier organize your imports using the TypeScript language service API.
Make sure that your import statements stay consistent no matter who writes them and what their preferences are.
A plugin that makes Prettier organize your imports (i. e. sorts, combines and removes unused ones) using the
organizeImportsfeature of the TypeScript language service API. This is the same as using the "Organize Imports" action in VS Code.
npm install --save-dev prettier-plugin-organize-imports
typescriptare peer dependencies, so make sure you have those installed in your project.
The plugin will be loaded by Prettier automatically. No configuration needed.
Files containing the substring
// tslint:disable:ordered-importsare skipped.
TL;DR: Make sure that you have either
@vue/compiler-sfc(for Vue 3.x) or both
vue-template-compiler(for Vue 2.x) installed.
npm i --save-dev @vue/compiler-sfc
npm i --save-dev @vue/component-compiler-utils vue-template-compiler
vueparser of Prettier splits the SFC (single file component) into its blocks and then runs each block through their respective "child" parser, i. e.
typescriptfor a block. This plugin would then preprocess the script content to organize the imports. However Prettier has a bug with the
preprocesshook when called in a child parser, which causes broken code around comments and other things. Therefore some work was necessary to do the import organizing on the parent parser level already; this requires some manual parsing using the aforementioned packages. Hopefully Prettier will fix this bug soon so that this whole readme section and the extra code can be deleted and it just works™️ again 🤓
If something doesn't work, you can try to prefix your command with
DEBUG=truewhich will enable this plugin to print some logs.
2.3.4fixes an issue with Vue 2 files.
2.3.3fixes a bug where default imports were removed erroneously.
2.3.1adds debug logs and fixes Vue.js support.
2.2.0adds a compiler options cache to improve performance.
2.1.0adds support for Vue.js (
2.0.0adds support for the parsers
babel-tswhich are only available since Prettier v2 (and thus the peer dependency has received a major bump).
This plugin acts outside of Prettier's scope because "Prettier only prints code. It does not transform it.", and technically sorting is a code transformation because it changes the AST (this plugin even removes code, i. e. unused imports). In my opinion however, the import statements are not really part of the code, they are merely directives that instruct the module system where to find the code (only true as long as your imports are side-effects free regarding the global scope, i. e. import order doesn't matter), comparable with
usingdirectives in C# or
#includepreprocessing directives in C. Therefore the practical benefits outweigh sticking with the philosophy in this case.