Antoine Mesnil

Developer, Designer & Solo entrepreneur

Tidy up your ES6 imports

Cover Image for Tidy up your ES6 imports

Introduction

Over the past years I've picked up many habits to keep my projects consistent and easy to maintain. One of them is to have imports with short paths, grouped and sorted that I can scan with just a glance and as I'm lazy like any developer it's done automatically.

Here is an example of how imports would change

screenshot of bad imports snippet

screenshot of good imports snippet

To achieve this change I did 3 things


1. Barrel Pattern

A barrel is a way to rollup exports from several modules into a single convenient module. The barrel itself is a module file that re-exports selected exports of other modules.

basarat gitbook

Instead of importing every single file everywhere, we use an intermediary. For each folder where we want a common export, we create an index.js file that will contain the exports for every file of the folder. But an example will be more understandable than a long explanation.

Image descriptionImage description


2. Uses aliases

I found 3 reasons to use aliases

  • It shortens paths to make it more readable
  • If you have to move a file, imports won't change
  • It makes the use of snippets easier (I have them to template the starts of my files)

Depending in your tech stack, you can will have different configs. For project like Create-react-app, React-native or anything using babbel / webpack :

First step is to install the babel plugin npm i babel-plugin-module-resolver or if you prefer yarn add babel-plugin-module-resolver

Then in the "babel.config.js" file, you add this config

babel config screenshot

when using Nextjs : Nextjs alias documentation when using Vitejs : Example of setup

when using typescript

tsconfig screenshot


3. Order imports

The last important thing I do to keep my imports clean, is to order and group them.

To do that automatically one tiny lib (prettier plugin) : https://github.com/trivago/prettier-plugin-sort-imports

I chose to use this library because prettier is used on every projects, it's easy to setup and fully configurable with regexes.

I know what you may think, regex and easy in the same sentence but for this use case it's pretty straightforward. Here is my personal config :

import order config

It makes 3 groups, one for external imports (libraries), one for internal imports (components, helpers, hooks...) and the last one for everything related to styles, styled-component...


😄 Thanks for reading! If you found this article useful, want more tips and follow my journey to create my own startup studio follow me on Twitter