Ts-node: module resolution at runtime is confusing

Created on 13 Jul 2017  路  4Comments  路  Source: TypeStrong/ts-node

Here's the minimal repro:

index.ts:

import { foo } from './foo';

console.log(foo);

foo.ts:

export const foo = 'ts';

foo.json:

{
  "foo": "json"
}

package.json:

{
  "dependencies": {
    "ts-node": "^3.2.0",
    "typescript": "^2.4.1"
  }
}
$ yarn
...
$ npx ts-node index.ts
json

$ tsc index.ts
$ node index.js
ts

$ npx ts-node index.ts
ts

AFAICT, ts-node defers to node's native require before resolving its internally compiled modules, which means the .json file on disk wins. I think this should be considered a bug though, since the module resolution is different from typescript's, and behavior between running ts-node and running tsc with node diverges.

wontfix

Most helpful comment

Ok, thanks for your explanation. Unfortunate, but understandable. Also, thanks for the great package!

All 4 comments

This is expected and not a bug. Feel free to make a PR for docs though. Changing any way that node.js requires is a bad idea.

Thanks for the response. I don't think I explained the issue clearly enough.

The problem is that running ts-node at dev time could have different results from running tsc to build production code and running that built javascript.

I'm not suggesting changing the way node.js requires. I'm suggesting ts-node behavior should match the behavior of tsc && node.

If you're saying this is a known issue but it's still a wontfix, I understand, it's a pretty weird edge case and I already have a workaround for my own case, I just wanted to make sure I explained the problem clearly. I think taking a close look at the minimal repro is probably the best way to understand.

Thanks for the extra explanation, I understand better now. Unfortunately I think this is still wontfix. I've given a similar answer with a different feature before (.js actually resolves over .ts, but TypeScript uses .ts over .js). I just wouldn't want to get into a situation where I'm messing with the node.js internal require pattern. The two approaches I saw was:

  1. Mess with the object keys of require.extensions to force .ts first (this may have unintended side-effects in the ecosystem, such as tools like https://github.com/maxogden/dependency-check which mirror node.js require order)
  2. Try to check .ts before every file load (bad when the .ts file doesn't exist, doubling the require time)

Ok, thanks for your explanation. Unfortunate, but understandable. Also, thanks for the great package!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

OliverJAsh picture OliverJAsh  路  3Comments

remojansen picture remojansen  路  4Comments

dakom picture dakom  路  3Comments

htonkovac picture htonkovac  路  4Comments

mattdell picture mattdell  路  4Comments