Can node
's module loader support TS's baseUrl
compiler option?
TS 2 introduced the baseUrl
compiler option, to effectively enable project relative require()
and import
requests.
However, this requires the module loader to support the same thing, as TS doesn't actually rewrite the request during transpilation. For tools like webpack, this is fairly straightforward.
Unfortunately, when using TS to develop node
applications (.i.e backend services, command line tools, electron desktop apps) there didn't seem to be a way to change node's module loader behavior.
Is there a way?
Yes!
Appreciating TS's position, here's a simple solution to the 90% use case for those of us using
node
, but wanting the convenience of usingbaseUrl
relativerequire()
calls without any fuss.This solution hooks
node
'srequire()
call, and resolves requests using thedirname
of "main" to mimicbaseUrl
. It therefore assumes thebaseUrl
compiler option was also set to the same directory where the source "main.ts" was located.To use, paste this tiny chunk of code at the top of your "main.ts".