Cannot find Typescript module even though tsc successfully manages to resolve it

It turns out that the problem was due to the fact that although both tsc and ts-node use baseUrl for absolute path resolution, neither of them perform any type of actual mapping from absolute to relative paths in the generated Javascript code. In other words, both the transpiled JS files and the code produced internally by ts-node end up having:

import  {MyClass} = require('my-module')

whereas I was expecting them to contain something like:

import  {MyClass} = require('../my-module')

which prevented node's module loader from finding the module. ts-node also did not work, I believe, because there was simply no tsconfig.json file to indicate the path mappings.

Although confusing IMO, and not properly documented, this is expected behavior, though, as discussed here. As of now, absolute to relative path mapping is not supported by Typescript (see https://github.com/Microsoft/TypeScript/issues/15479).

In order to avoid the situation known as path hell, which means having very deep relative import paths, I found module-alias and tsmodule-alias to be very useful. These modules alter the behavior of the module loader so that it automatically maps aliases to relative paths.

For more information about the problem, refer to this issue on Github.


Another solution that may be relevant is to run node with NODE_PATH=dist node dist/index.js. This essentially specifies to node what path each absolute import (relative to baseUrl) should use