Import Sorter — Complete Guide to JavaScript & TypeScript Module Organization
A comprehensive developer reference for organizing, grouping, and sorting ES6 and TypeScript import statements. Learn how deterministic module ordering improves code readability, streamlines pull request reviews, prevents Git merge conflicts, and preserves critical side-effect execution guarantees.
1. What is an Import Sorter?
An import sorter is a developer productivity utility that scans the top of JavaScript or TypeScript source files and systematically reorganizes import declarations according to architectural conventions. In modern web development, modules frequently import tens of dependencies ranging from standard runtime built-ins and third-party npm packages to internal path aliases and local sibling components.
Without automated organization, imports accumulate randomly as features evolve. An import sorter categorizes each declaration into distinct tiers, alphabetizes paths within each tier, optionally alphabetizes named specifiers inside curly brackets, and leaves all downstream functions, JSX elements, and non-import code 100% untouched.
2. Why Import Sorting Matters
Eliminating Git Merge Conflicts
When multiple engineers add new imports to the bottom of an unorganized import block, Git merges produce immediate line collisions. Deterministic alphabetical placement ensures that imports are added at predictable locations, eliminating merge conflicts.
Immediate Dependency Clarity
Separating core runtime modules, third-party libraries, and internal project abstractions allows code reviewers to instantly distinguish external dependencies from local component coupling at a single glance.
Clean Pull Request Diffs
Standardized formatting prevents noisy diffs where one developer manually reorders imports while modifying a unrelated feature. Every commit maintains consistent header cleanliness.
3. How to Use the Import Sort Preview
- Input Your Code: Paste your source code directly into the Original Code editor pane or click Upload File to load a local
.ts,.tsx,.js, or.jsxfile. - Configure Sorting Preferences: Toggle group separation, alphabetical sorting, case-sensitivity, natural numerical ordering, or named specifier sorting.
- Set Custom Aliases: Specify project-specific alias prefixes (e.g.
@/,~/,@core/,@ui/) so that scoped third-party packages (like@radix-ui/react-slot) are correctly kept in the third-party tier. - Sort & Inspect Differences: Click Sort Imports. View the transformed code in the editor or switch to the Unified Diff tab to inspect changes.
- Export Clean Code: Click Copy Sorted Code to copy to your clipboard or Download to save the formatted file.
4. Before and After Import Sorting Example
Consider an unsorted React component header containing a Node built-in, third-party packages, internal project aliases, relative imports, type imports, a side-effect polyfill, and a stylesheet:
Before: Unsorted Source
import "./polyfill";
import { useState } from "react";
import Button from "./Button";
import axios from "axios";
import fs from "node:fs";
import type { User } from "@/types/user";
import "./styles.css";
import React from "react";
import { formatDate } from "@/utils/date";
export function Profile() {
const [data, setData] = useState(null);
return <Button />;
}After: Deterministically Sorted
import "./polyfill";
import fs from "node:fs";
import axios from "axios";
import React, { useState } from "react";
import type { User } from "@/types/user";
import { formatDate } from "@/utils/date";
import Button from "./Button";
import "./styles.css";
export function Profile() {
const [data, setData] = useState(null);
return <Button />;
}Notice how the side-effect polyfill import "./polyfill" remains at the very top as a safety barrier, while Node built-ins, third-party libraries, project aliases, and relative components are cleanly grouped with blank line separations.
5. Configure Custom Import Groups & Project Aliases
A common defect in naive regex-based formatters is classifying any module path starting with @ as an internal project alias. However, in modern JavaScript ecosystems, hundreds of popular third-party packages are scoped under organizations:
@tanstack/react-query— Third-party scoped package@radix-ui/react-dialog— Third-party scoped package@types/node— Third-party type definitions@/components/Button— Internal project alias@core/api— Configured monorepo package or path alias
ToolMono solves this by requiring project aliases to be explicitly declared (defaulting to @/, ~/, and #). Scoped packages matching @scope/pkg that are not in your configured alias list are kept in the Third-party group where they belong.
6. TypeScript & React (JSX/TSX) Support
ToolMono provides first-class support for modern TypeScript and React idioms:
TypeScript Type-Only Imports
Handles both declaration-level type imports (import type { Props } from "./types") and TypeScript 4.5+ inline specifiers (import { type Props, Component } from "./comp") without stripping type modifiers.
Directives Prologue Protection
React Server Components and Next.js require "use client" or "use server" to appear at the very first line of a module. ToolMono guarantees that sorted imports never move above directive prologues.
7. Why Side-Effect Imports Need Special Handling
In ECMAScript Modules, side-effect imports (declarations without exported bindings like import "./polyfill"; or import "reflect-metadata";) execute immediate global code during evaluation.
Moving an import statement across a side-effect import can cause severe runtime bugs:
- Polyfill Timing: A polyfill must execute before other modules instantiate classes or access global APIs (e.g.
window.fetchorcrypto.subtle). - CSS Cascade Order: Global stylesheet imports dictate rule precedence in browser rendering engines. Changing stylesheet import order can alter layout styles.
- Dependency Injection: Frameworks like InversifyJS or Angular rely on
reflect-metadatabeing loaded prior to any decorated class definition.
By default, ToolMono operates in Side-Effect Partition Mode: side-effect declarations serve as immovable barriers, and regular imports are sorted within each partition without ever crossing a side-effect boundary.
8. Import Sort Preview vs. Prettier, ESLint & Biome
| Feature | ToolMono Import Sorter | ESLint (import/order) | Prettier (Sort Plugin) | Biome |
|---|---|---|---|---|
| Zero-Installation Preview | Yes (Instant Web UI) | No (Requires npm setup) | No (Requires plugin install) | No (Requires CLI) |
| Interactive Diff Preview | Yes (Side-by-side & Unified) | No (CLI output) | No (File rewrite) | Terminal diff only |
| Side-Effect Partitioning | Yes (Default Safe Barrier) | Configurable | Partial | Configurable |
| Directive Prologue Safety | Strictly Preserved | Requires rule config | Preserved | Preserved |
| Primary Use Case | Quick cleanup & diff verification | CI/CD linting enforcement | Automated format-on-save | All-in-one rust toolchain |
9. Common Import Sorting Problems & Solutions
Issue: Multiline imports left dangling lines after sorting
Cause: Naive line-by-line replacers only replace the first line of an import, leaving orphan closing brackets in the body.
Solution: ToolMono parses the full start-to-end token range of multiline statements, replacing the entire declaration atomically.
Issue: Next.js "use client" directive broke after formatting
Cause: The sorter moved import declarations to line 1, pushing "use client" into the module body.
Solution: ToolMono recognizes directive prologues and ensures sorted imports are always injected below directive lines.
Issue: Comments above imports disappeared or moved to wrong lines
Cause: Comments were discarded during parsing.
Solution: ToolMono binds leading comments directly to the import AST node, moving comments alongside their declarations.
10. Frequently Asked Questions
What does an import sorter do?
An import sorter analyzes the top of your JavaScript or TypeScript source files and reorganizes import declarations into clean, deterministic tiers (Node.js built-ins, third-party packages, internal aliases, relative imports, and stylesheets) while preserving non-import application code.
Does sorting imports change program behavior?
For standard value and type imports, reordering does not alter runtime behavior. However, for side-effect imports (like polyfills, initialization scripts, or global CSS), order matters. ToolMono preserves side-effect imports in their original declaration sequence by default so module initialization remains safe.
Can I sort TypeScript imports?
Yes. ToolMono supports TypeScript 'import type { FC } from react' statements as well as inline specifiers 'import { type FC, useState } from react', preserving type-only modifiers without converting or stripping them.
How should side-effect imports be handled?
Side-effect imports (e.g. import './polyfill' or import 'reflect-metadata') execute code upon module evaluation. ToolMono treats them as barriers by default, sorting imports within each partition without moving code across side-effect boundaries.
Can I configure aliases and group order?
Yes. You can customize internal project aliases (such as @/, ~/, @core/, @ui/) and toggle blank lines between groups, alphabetical sorting, case-sensitive sorting, and named specifier sorting.
Does this tool upload my source code?
No. 100% of parsing, token extraction, group categorization, and code reconstruction execute locally in your web browser memory. No source code or file data is ever transmitted across the network.
What is the difference between an import sorter and Prettier?
Prettier focuses on line wrapping, quote styles, and whitespace formatting without reordering statements. An import sorter reorganizes the semantic sequence of import declarations into structured architectural tiers.
How can I enforce import ordering automatically in a project?
You can configure ESLint with the 'eslint-plugin-import' (rule 'import/order') or use Prettier with '@ianvs/prettier-plugin-sort-imports'. In modern toolchains, Biome provides built-in import sorting via 'biome check'.
11. References & Standards
- ECMA-262 (ECMAScript Language Specification) — Section 16.2.2 Imports
- TypeScript Documentation — Type-Only Imports and Exports
- Node.js Documentation — Subpath Imports and Built-in Module Resolution
- ESLint import/order Specification
- ToolMono Package.json Explorer • Dependency Tree Viewer • Text Diff Checker