Title: Avoiding relative imports in Javascript, TypeScript, Webpack and Jest
Slug: avoiding-relative-imports-in-javascript-typescript-webpack-and-jest
Date: 2021-11-09 23:00:00
Author: Kartones
Lang: en
Tags: Development, Javascript, Patterns & Practices, Typescript
og_image:
Description: This blog post discusses how to avoid or remove relative imports in JavaScript projects by using module aliases in Webpack and Babel, as well as configuring path mappings in TypeScript and Jest. The goal is to make imports more readable and maintainable.


A quick post to serve as a quick reference for myself on how to avoid/"remove" relative imports in big Javascript projects, monorepos, etcetera.

If you want some context on why this can be a good idea, check for example the article [Importing with Absolute Paths using webpack in JavaScript/TypeScript](https://spin.atomicobject.com/2017/10/07/absolute-paths-javascript/).

A five seconds summary is: 

Converting this unreadable and hard-to-maintain-without-an-IDE monster...
```
import { whatever } from '../../../../../../../shared/a-category/componentA';
```

...into something actually meaningful when read:
```
import { whatever } from '@sharedComponents/a-category/componentA';
```


The first step is to configure [Webpack module aliases](https://webpack.js.org/configuration/resolve/) and Babel aliases via the [babel-plugin-module-resolver](https://www.npmjs.com/package/babel-plugin-module-resolver) plugin.

Then, for Typescript we should configure [path mappings](https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping)


And if you use Jest for tests, it also needs [some configuration](https://jestjs.io/docs/configuration#modulenamemapper-objectstring-string--arraystring) to allow proper mocking of aliases.
