swc-project / swc-node

Faster ts-node without typecheck
MIT License
1.69k stars 69 forks source link

feat(register): @swc-node/register/esm use TypeScript resolver #727

Closed cm-ayf closed 9 months ago

cm-ayf commented 10 months ago

Currently @swc-node/register/esm has its own implementation in register hook to resolve imports like ./foo or ./foo.ts. However, the resolution should be aligned with that by TypeScript (specifically tsserver) which is far more complicated.

This PR just uses TypeScript resolver in register hook. In this way, the resolution will respect setting files such as tsconfig.json, package.json, and so on. Thus, this PR potentially fixes issues #710 and #724, and adds support for paths in tsconfig.json.

As of the performance issue, it can be said that TypeScript resolver will not search deep into node_modules; if parentURL is in node_modules the resolver falls back to default one, and so does if the resolution result. Note that TypeScript resolver itself is already fast enough.

This PR also fixes the problem where node --watch --loader @swc-node/register/esm main.ts does not refresh after editing main.ts. this might have been a bug on the previous implementation.

CLAassistant commented 10 months ago

CLA assistant check
All committers have signed the CLA.

cm-ayf commented 10 months ago

With a little fix, I have verified that issues #710 and #724 will be fixed. However, paths in tsconfig.json was not properly handled. The reason for this is not clear, but I believe this PR is still a big step forward.

DouglasGabr commented 9 months ago

This solves an issue I'm facing. With "moduleResolution": "Bundler", typescript accepts imports like import { foo } from "./test.model" (file name is test.model.ts), but @swc-node/register/esm fails to resolve that file since it thinks .model is the file extension.

Current workaround that worked for me is changing the import to import { foo } from "./test.model.js".

Just tested with this PR patched code and it works for both cases.