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
To achieve this change I did 3 things:
- Barrel pattern
- Aliases
- Order imports
1. Barrel Pattern
A barrel is a way to roll up exports from several modules into a single convenient module. The barrel itself is a module file that re-exports selected exports of other modules.
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.
2. Uses aliases
I found 3 reasons to use aliases
- It shortens paths to make them 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 on your tech stack, you can have different configs. For projects like Create-react-app, React-native, or anything using babel / webpack :
The 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
when using Nextjs: Nextjs alias documentation
when using Vitejs/Vue: Example of setup
when using typescript:
3. Order imports
The last important thing I do to keep my imports clean is to order and group them.
To do that automatically I use 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 project I work on, it's easy to setup and fully configurable with regexes.
I know what you may think, regex and easy in the same sentence must be a joke but for this use case it's pretty straightforward. To verify the config works properly I use Regexr with my targeted paths. Here is my personal 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...