Jake Worth

Organizing Your JavaScript Imports

August 31, 20211 min read

  • javascript

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

Why is This 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';

Conclusion

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.


Blog of Jake Worth, software engineer in Maine.

© 2021 Jake Worth.