Webpack— eliminating long imports — Part 1

Zsolt Gömöri
2 min readMar 22, 2019

It’s completely usual to import the desired functions, resources or whatever at the top of each file. I was working with these annoyingly long phenomena from the beginning, but I realized that this somewhat pollutes the readability and it’s even quite confusing — at least to me. The latter statement is especially right when the structure is extremely nested.

Apart from the framework you use in conjunction with Webpack, let me take the opportunity and demonstrate the solution abstractly.

Fortunately, Webpack provides all the tools that need to be built into the configurations in order to achieve the desired functionality.

The exact name of the property we’ll work with is called resolve. Let me introduce its usage via an example:

What does it do?

Actually, as the property name suggests, it resolves the ~ symbol with the path we passed — src/ in this case. Obviously, you may create additional aliases that fit your preferences.

As a result, the imports at the top of each file are abbreviated.

Additionally, it’s much more readable — only if the user knows what ~ means.

Caveats

  • If there’re some other 3rd-party libraries that participate in the usage of imports within the project, they should also be configured. I have encountered with ESLint and Jest along the way, but that’d rather worth another article in which I specify the exact configurations — will be continued in part 2.
  • I’d discourage you to go ahead and change all the relevant paths so that bite off a few characters. That sounds bad, doesn’t it? What I propose is using it only in special cases in which you likely to go up to the root directory — src/ is a great example if you’re developing in React.

That’s all for the first part of the series. In the second part, I’ll write about specific configurations in connection with Jest and ESlint. Hopefully, you’ve gained some new insights. See ya’ there!

Feel free to hit me up on Twitter and ask questions in the comment section.

--

--