Avoiding relative imports in Javascript, TypeScript, Webpack and Jest

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.

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 and Babel aliases via the babel-plugin-module-resolver plugin.

Then, for Typescript we should configure path mappings

And if you use Jest for tests, it also needs some configuration to allow proper mocking of aliases.

Tags: Development Javascript Patterns & Practices Typescript

Avoiding relative imports in Javascript, TypeScript, Webpack and Jest article, written by Kartones. Published on