egoist / tsup

The simplest and fastest way to bundle your TypeScript libraries.
https://tsup.egoist.dev
MIT License
8.88k stars 213 forks source link

__dirname value differs from tsc and tsx #915

Open jeffersonfelixdev opened 1 year ago

jeffersonfelixdev commented 1 year ago

When I call __dirname in tsc or tsx its value is the current directory. But in tsup the value is the entrypoint directory.

Example:

Suppose there is a project where the entry point is /home/project/src/server/index.ts:

import '../modules/example'

And the file /home/project/src/modules/example.ts:

console.log(__dirname)

When I build from tsc or run using tsx, the result is:

/home/project/dist/modules/

But when I build from tsup the result is:

/home/project/dist/server

Is there a way to get same result from tsc and tsx?

Upvote & Fund

Fund with Polar

jeffersonfelixdev commented 1 year ago

After a long research, I think it's a problem with esbuild that introduces a compatibility with ESM (that uses import.meta) and CJS (that uses __dirname).

I moved to process.cwd() to get the root dir and the path is the same across tsx (dev) and tsup (prod).

jeffersonfelixdev commented 1 year ago

Ops! I got it!

I was building all files with target set to src folder, but tsup by default bundle files. So when I start the application, only the entrypoint file is used.

I solved it on turn off bundle option.

ramblingenzyme commented 1 year ago

@jsfelix is this related to https://github.com/egoist/tsup/issues/958?

Leo-Henrique commented 3 months ago

I don't understand why dirname references the folder of the file executed when building with tsup. I just can't get the current directory of the file where I call dirname :(