How to Organize JavaScript Imports
- 2 minutes read - 375 wordsThe import
statements at the top of a JavaScript component file can be a
confusing, duplicative, churning mess. Is there a way to organize them that
makes sense and scales? In this post, I’d like to share the way I handle this detail.
Who Cares?
Wait; who cares? Isn’t this like discussing the color of the bike shed?
Years of programming with other humans has taught me that, for loosely-defined tasks like this, any convention is better than no convention. Without it, you’ll see in many, many codebases:
- Inexplicable whitespace (or lack of)
- Duplicated references to libraries
- Duplicated imports
- Unused imports
- No logical organization
I’m talking about something like this:
import React from 'react';
import { useState } from 'react';
import DashboardButton from './DashboardButton';
import { ShortTime } from '@app/common/dates';
import { Route } from 'react-router-dom';
import './Dashboard.scss'
import Dashboard from '@app/Dashboard/Dashboard;
import { ShortDate, ShortTime } from '@app/common/dates';
import Dashboard from './Dashboard';
We don’t tolerate this in our code. Why should it be acceptable in our import
statements? If you believe that all code can be readable and tidy, read on!
My Approach
My approach has a couple of tenets:
- Imports are grouped outside-in
- Groups are separated by one line of whitespace and alphabetized
- Libraries are only referenced once and no imports are duplicated
Imports are grouped outside-in. Third-party libraries, then shared/common libraries in our codebase, then files in our project, then relative imports (which I generally avoid), and then stylesheets.
Groups are separated by one line of whitespace and alphabetized. Readability and convention!
Libraries are only referenced once an no imports are duplicated. Goodbye duplication and redundancy!
Here’s an example:
// Third party libraries, alphabetized
import React, { useState } from 'react';
import { Route } from 'react-router-dom';
// Shared libraries, alphabetized
import { ShortDate, ShortTime } from '@app/common/dates';
// Files in our project, alphabetized
import Dashboard from '@app/Dashboard/Dashboard';
// Relative imports (as needed), alphabetized
import DashboardButton from './DashboardButton';
// Stylesheets, alphabetized
import './Dashboard.scss'
// Component here!
Tools have come and gone that helped automate this. Whatever your approach, take some time make it a habit, with our without tooling. I think that it’s part of writing readable, scalable JavaScript code.
Thanks to Adam Rowe for helping me refine these opinions in 2022.