Module aliasing in Webpack

Problem, Solution, Complications

Vikas Singh
May 31, 2019 · 3 min read

Initially, when you start off a project, you don’t mind writing long relative paths and ignore all the troubles that come with it.

Problem

But as your project starts to scale past a certain point of complexity, you’ll find traversing up and down your file system is time-consuming and error-prone. Even with code-completion features like IntelliSense in place (supported by almost every IDE), this can become more challenging as your codebase grows.

Just imagine a situation where you are changing the directory structure of a module in your project. This will break all the module references and you will be forced to change all occurrences of the module throughout your project. It will be a daunting task!

Moreover, see how ugly it looks?

Solution

Webpack allows you to create aliases to import or require certain modules through the resolve.alias property in your config without any additional plugins.

Changes in webpack.config.js

Concept of aliasing modules in Webpack can help you to turn the above file into this clean version.

Neat, clean and customized with so many benefits

Consequence

Once we start using aliases, IntelliSense stopped working for these imports in VSCode.

Luckily there is an extension available to remedy the situation, Jump To Alias File

Image showing Jump To Alias File in action

Another way is to let VSCode know how to resolve these aliases by adding a jsconfig.json file to your project at the root.

{
"compilerOptions": {
"target": "es2017",
"allowSyntheticDefaultImports": false,
"baseUrl": "./",
"paths": {
"config/*": ["src/config/*"],
"store/*": ["src/store/*"],
"utils/*": ["src/utils/*"]
}
},
"exclude": ["node_modules"]
}

That pretty much sums it up! If you have any questions or suggestions, don’t forget to leave a comment down below.

Have you enjoyed reading this blog? If yes, then click on the 👏 icon and share this article! Also, feel free to leave a comment.

Groww Engineering publishes technical pieces, latest knick-knacks in the coding world and convenient ways to tackle common programming problems.

Read more of our articles here.

Groww Engineering

Groww Engineering and Tech

Vikas Singh

Written by

I code to bring wow experience for users

Groww Engineering

Groww Engineering and Tech

More From Medium

More on Webpack from Groww Engineering

More on Webpack from Groww Engineering

8 Tips to keep your code clean in React

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade