Skip to content

Better Readability with Aliases for Typescript Module Imports

MacBook Pro showing programming language


Lars W├Ąchter has a great article on how to implement module aliases on Typescript, thus improving your code from looking something like this:

import { User } from '../../user/model';
import { Article } from '../../article/model';

import { Cache } from '../../../../cache';
import { MongoDB } from '../../../../mongodb';

Into something that can look like this:

import { User } from '@modules/user/model';
import { Article } from '@modules/article/model';

import { Cache } from '@services/cache';
import { MongoDB } from '@services/mongodb';
MacBook Pro showing programming language
I just feel like I need to have my code organized- I sleep better at night that way.
Photo by Emile Perron

Fantastic!

However, I encountered an issue when using the zeit/pkg packaging tool, which bundles your node js application into a single executable file.

The problem was that pkg didn’t support module aliases, the way Lars solved it above. Doing a little bit of research, I found ef-tspm which is a post typescript compilation build step which reverts those module aliases (e.g. @/your-dir/your-file ) back into its pre alias form (e.g. ../../../../your-dir/your-file). This form can be handled by the pkg tool.

What will my build process look like?

  1. tsc – Compile your Typescript code into Javascript.
  2. ef-tspm – Revert the module aliases found in your Javascript code.
  3. pkg . – Package your node js application.

Cheers!

References

  1. https://dev.to/larswaechter/path-aliases-with-typescript-in-nodejs-4353
  2. https://github.com/vercel/pkg/issues/249#issuecomment-643117032

New to sapalo.dev?

Hi there reader! My name is Darren and I write about technology, learning, and gaming for mid to senior level software engineers. I love learning and finding lessons (and mistakes) in things that I do.

Sharing what we learn enables us to encourage, uplift, and empower the next set of engineering problem solvers. Writing them down also reminds me to seal the lesson in and not forget them!

I have a series of mental models that helps you think and strategize for problems whether in engineering or in your personal life. I also share short stories about reflections of my life, studying the similarities of playing competitively both in games and in performance at work.

Here are some trending things I’ve been talking about lately:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.