Node.js supports import maps
- Published at
- Updated at
- Reading time
- 1min
In growing JavaScript projects it is very common to end up with very long import paths navigating up and down the file tree (
). 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
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
and also directly reference
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!
Join 6.1k readers and learn something new every week with Web Weekly.