Two ways to use absolute import paths in Node.js
Published on in JavaScript and Node.js
Last updated on
Say goodbye to ../
times million
and use absolute import paths from the app's root directory instead.
Two contenders: Basetag and Sultan's sexy-require
! ðĪš
Table of contents
Sultan's sexy-require
Example usage of the
sexy-require
npm package by Sultan:
// Before, unclear what's being required ð
const user = require('../../../database/user')
// After, absolute path from the app's root dir ð
const user = require('/database/user')
// Alternatively, using an alias configured in a `.paths` file ð
const user = require('$db/user')
sexy-require
overrides Module.prototype.require
,
so in other files
require()
points to sexy-require
's require
function
which supports absolute paths and path aliases.
Pros
- Simple to set up: install the package and require it in your main application file.
- Supports path aliases.
- The name!
Cons
- Breaks VS Code's IntelliSense.
- Breaks path autocompletion in VS Code.
- Supports only
require()
, notimport
.
Basetag
Example usage of the Basetag npm package by Jannik:
// Before, unclear what's being required ð
import user from '../../../database/user'
const user = require('../../../database/user')
// After, $ points to the app's root dir ð
import user from '$/database/user'
const user = require('$/database/user')
Basetag creates a symlink,
or something called a junction on Windows,
so that node_modules/$
points to the app's root directory.
Pros
- Works with VS Code's IntelliSense.
- Path autocompletion works in VS Code.
- Supports both
require()
andimport
.
Cons
- No way to configure path aliases.
- The symlink gets removed by npm when installing or removing packages,
so you need to e.g. create a
postinstall
npm script as instructed in the package's readme. Not difficult, but a little hassle.
Which one to use
I'm not sure which one I like more:
- Better VS Code support of Basetag.
- The name Sultan's
sexy-require
.
Just kidding â
use Basetag,
good IDE support is more important.
Plus it also supports import
statements.
Update in 2023
There are probably better solutions than these two.
Besides, I wrote this post mainly because I found the name "Sultan's sexy-require
" so sweet.
Some time ago I came across a blog post saying that Node.js supports import aliases natively since v14. I haven't tested that, but it looks promising.