Avoiding long relative paths when doing imports in Node.js
Aren’t you tired of doing something like this import AnyModel from '../../../models/AnyModel'
?
Well, if you are not tired like me, you can skip this post and I envy you haha.
But if you are tired like me, imagine that your directory structure is something like this:
myProjectFolder/
|--main.js
|--app/
|--models/
| |--Article.js
| |--Post.js
|--workers/
|--SomeWorker.js
So if you want to use Article.js
inside SomeWorker.js
, you will need to do import Article from '../models/Article.js'
. I hate those '..'
, they annoy me, and that import doesn’t have many '..'
, but if the loaction of SomeWorker.js
or any file where you need to include Article.js
is far far away the number of '..'
is greater.
So yesterday, I was searching for a solution and I came across with app-module-path-node.
An awsome module that free you of the relative paths. You only need to:
npm install app-module-path --save
- In your
main.js
,app.js
orwhatever.js
addimport 'app-module-path/register';
Now instead of import Article from '../models/Article.js'
I can do import Article from 'app/models/Article.js'
and I am very much happier than before!!
If you know another solution, please post it in the responses and I will update the post!
hope you enjoy reading this post, as much as I enjoyed writing it!
You can follow me on Twitter.
Mariano Matayoshi (matayoshi.mariano@gmail.com)