ts-node icon indicating copy to clipboard operation
ts-node copied to clipboard

Wrong base path determination when ts-node/esm loader is used

Open ThePlenkov opened this issue 1 year ago • 4 comments

Current behavior

Let's say I have a subpackage in my workspace which I want to use a module .

So i have a folder like tools/codegen with file like index.mts with a content like

#!/usr/bin/env -S node --loader ts-node/esm
const t = await true;

So without tsconfig.json tsc will not work. So let's add tools/codegen/tsconfig.json

{
    "extends": "@tsconfig/recommended/tsconfig.json",
    "compilerOptions": {
        "module": "ESNext",
        "target": "ES2017",
        "moduleResolution": "node16",
        "esModuleInterop": false
    },
    "ts-node": {
        "esm": true
    }
}

So with this config IDE already doesn't give error. tsc command also works fine.

In my tools/codegen/package.json i have "bin":"index.mts"

So after install I 'm able to run npx codegen from tools/codegen

However if I run it from the root of the monorepo it seems that ts-node is not smart enough to determine what is the base folder for executed file. So command npx codegen from the root level triggers top-level await TypeScript error which occurs without tsconfig.json

To be able to run npx codegen from root level i use "workspaces" : "tools/*" in my root package.json

Expected behavior

I expect that ts-node should understand from where it is called. Indeed node is called with some path and that path can be used as a base path for config determination.

It should not matter from where I call my npx codegen command - it should work similarly becase config should be linked to the executed file and not to the folder from where I run.

In my case I don't have tsconfig.json - but in more complicated case I might have one but with different set up.

Example

I've prepared a sample project showing this behavior https://github.com/ThePlenkov/ts-config-top-level-await-issue

Thanks!

ThePlenkov avatar Apr 11 '23 14:04 ThePlenkov

I switched to tsx and everything works 👌

crobinson42 avatar Nov 06 '23 16:11 crobinson42

Hi @crobinson42 could you please elaborate more what did you exactly do? Just renamed files? Thanks!

ThePlenkov avatar Nov 07 '23 14:11 ThePlenkov

Oh ok! So tsx is something new for me. I guess you meant https://github.com/esbuild-kit/tsx. I just updated my sample https://github.com/ThePlenkov/ts-config-top-level-await-issue and indeed tsx just works smoothly. Many thanks for this tip! However I'll keep the issue open here as it's ts-node realted

ThePlenkov avatar Nov 07 '23 15:11 ThePlenkov

tsx is fine as long as you won't use decorators which esbuild doesn't support. esbuild has not type support.

randre70 avatar Feb 23 '24 11:02 randre70