Jake Worth

Organizing Your JavaScript Imports

Published: August 30, 2021 2 min read

  • javascript

Is there a way to organize JavaScript import statements that makes sense?

Perhaps you have a large component with a ton of imports, and they’re a disorganized mess.

Should you alphabetize them? Or break them up into default and named exports?

JavaScript import statements can be a confusing, churning mess. In this post, I’d like to share the way I handle this part of writing JavaScript.

Why This Is Necessary

Years of programming with other humans has taught me that any convention is better than no convention. Without some policy the top of a non-trivial JavaScript file is a disorganized wasteland. Inexplicable extra spaces, duplicated imports, unused imports, no kind of logic; name an issue and I can find it in a large JavaScript codebase.

Code is at least partially for humans and that includes the top of the file. Let’s make it readable!

Grouped and Alphabetized

Below is the convention I’ve followed for about three years. Imports are broken into three groups, alphabetized among themselves, with a space between each group:

  • Libraries
  • Components from our codebase
  • Utility functions from our codebase
// 📕 Libraries, alphabetized
import * as React from 'react';
import { Route } from 'react-router-dom';

// 🧩 Components, alphabetized
import { Dashboard } from './Dashboard';
import { Flash } from './Flash';

// 🔧 Utility functions, alphabetized
import { AuthenticatedRoute } from 'utils/AuthenticatedRoute';
import { AuthorizedRoute } from 'utils/AuthorizedRoute';


I’d love if there was a tooling solution for this problem. As a Vim user, I used vim-import-js for years, but I haven’t been able to use that library since 2018 (closed issue here). Doing it by hand is not ideal but I still prefer the benefits over the extra work.

Whatever your preference, find a style that works and apply it.

✉️ Get better at programming by learning with me. Subscribe to Jake Worth's Newsletter for bi-weekly ideas, creations, and curated resources from across the world of programming. Join me today!

Blog of Jake Worth, software engineer in Maine.

© 2022 Jake Worth.