Published at
Updated at
Reading time
1min
This post is part of my Today I learned series in which I share all my web development learnings.

In growing JavaScript projects it is very common to end up with very long import paths navigating up and down the file tree (../../../src/lib/whatever/index.js). This isn't only terrible to read but can also be hard to refactor if you move files around.

To make things a bit easier, bundlers or the TypeScript compiler allow you to define path aliases (@lib/whatever/index), but I usually try to avoid bundling my Node.js applications to keep the complexity low. Today I learned that Node.js allows you to set path aliases with import maps.

Let's say you have this Node.js code using ESM.

import { getAuthenticatedUser } from "./src/lib/auth/user.js";
import database from "./src/lib/db/index.js";

// more stuff...

While this isn't the worst, the file paths could be way cleaner. To set aliases, head into your package.json and define an imports object.

{
  "imports": {
    "#auth/*": "./src/lib/auth/*.js",
    "#db": "./src/lib/db/index.js"
  },
}

Custom import paths need to start with a # and thanks to these two quick lines you can now shorten any import going into ./src/lib/auth and also directly reference ./src/lib/db/index.js with three characters (#db).

import { getAuthenticatedUser } from "#auth/user";
import database from "#db";

// more stuff...

Sweet! But does it work everywhere? Or is this a new Node.js thing?

Nope, this isn't new. Import maps are supported in Node.js since v14 (we're currently on v22 LTS), so your Node.js environment will probably support them already. Have fun shortening some paths!

If you enjoyed this article...

Join 6.1k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles