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 https://webpack.js.org/configuration/resolve/ and Babel aliases via the 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 configuration to allow proper mocking of aliases: https://jestjs.io/docs/configuration#modulenamemapper-objectstring-string--arraystring

Avoiding relative imports in Javascript, TypeScript, Webpack and Jest published @ written by

Comment Share @ Twitter Share @ Linkedin Share @ Mastodon