Setup Aliases for Your JavaScript Project with Babel
Have you ever imported a file like so import file from "../../../file";? This is called import hell and it’s crap! Not only does it make code look ugly but sometimes (especially for noobs like me) it can be difficult to find the correct path and then we end up with eslint (import/no-unresolved) warnings when linting.
Let’s make life a little easier by creating alias’.
Prerequisite
A JavaScript project with Webpack and Babel setup. Check out my post of How to Setup a JavaScript Project with Webpack, Babel + SCSS
Step 1
- Open up your terminal and
cdinto your project npm i babel-plugin-module-resolveror if you preferyarn add babel-plugin-module-resolver
Step 2
- Go to your
babelrcfile. If you don’t have one yet, create one in the root of your project so it’s in line with yourwebpackfile(s). To create one just type the following in your terminaltouch .babelrc - Add the following:
{
...
"plugins": [
["babel-plugin-module-resolver",
{
"alias": {
"@pages": "./src/app/pages",
"@helpers": "./src/app/helpers",
"@services": "./src/app/services",
"@styles": "./src/styles",
}
}
]
]
}You can call your alias’ anything you like and create as many as you like. I prefer to add an @ sign in front of mine. You don’t have to.
And that’s it! All you have to do now is to change import file from "../../../file"; to whatever you named your alias e.g. if file.js is stored in the helpers folder just do this: import file from "@helpers/file";
Thanks for reading!
If this was helpful, I’d appreciate it if you gave this post a 👏, a share among your network and if you don’t already, a follow would be great.
Please also consider subscribing to Medium with my referral link. Medium is a great platform for learning and it’s what I use to stay up to date with what’s happening in the tech space as well as learn from other developers’ experiences.
Your subscription would directly support me and many other Medium writers.






