Skip to content

Rewrite __dirname/__filename to be relative from asset.filePath #7611

@LekoArts

Description

@LekoArts

🙋 feature request

This is a more detailed report of #5090 and one that I put up after following some private conversions with the Parcel Core Team to discuss the specifics in the open.

This feature (request) addressed one bulletpoint here: #2493

Rewrite __dirname and __filename. Currently we don't do this for Node targets, but we probably should so that they refer to the source file rather than the dist.

🤔 Expected Behavior

file.ts:

console.log(`${__dirname}/foo/bar`)

Gets compiled with Parcel to JS into the directory .cache/compiled.

.cache/compiled/file.js:

console.log(`${__dirname + "/../.."}/foo/bar`)

😯 Current Behavior

file.ts:

console.log(`${__dirname}/foo/bar`)

.cache/compiled/file.js:

console.log(`${__dirname}/foo/bar`)
// Which will result in `.cache/compiled/foo/bar`

💁 Possible Solution

First step would be to set a default for node target. That could/would be:
Treat it as relative from options.projectRoot (what is shown in the expected behavior example).

So for example: If outputDir is .cache/compiled and current cwd()/projectRoot is / the relative path to it would be ../../

In a next step options similar to https://webpack.js.org/configuration/node/#node__dirname could be added.

🔦 Context

This might also impact #6925 maybe?

Example Use Case

/usr/project/file.ts:

console.log(`${__dirname}/foo/bar`)

/usr/project/.cache/compiled/file.js:

console.log(`../../foo/bar`)

/usr/project is then the projectRoot because the rest of the scripts runs from this root directory and then the file.js is accessed.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions