Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

import.meta.url returns relative path #9

Closed
cusxio opened this issue Aug 26, 2021 · 5 comments
Closed

import.meta.url returns relative path #9

cusxio opened this issue Aug 26, 2021 · 5 comments

Comments

@cusxio
Copy link

cusxio commented Aug 26, 2021

https://nodejs.org/api/esm.html#esm_import_meta_url

In the docs, it says that import.meta.url returns an absolute url, but when I tried it with the example in the examples folder, import.meta.url returns a relative path.

I'm trying to replicate __dirname.

Reproduction: https://github.com/cusxio/vite-plugin-node-import

@axe-me
Copy link
Owner

axe-me commented Aug 26, 2021

are you using it in ESM code?

__dirname is not available in esm anymore, see https://nodejs.org/api/esm.html#esm_no_filename_or_dirname

@cusxio
Copy link
Author

cusxio commented Aug 27, 2021

ah I see! Wasn't aware of that. Thank you!

@cusxio cusxio closed this as completed Aug 27, 2021
@cusxio cusxio reopened this Aug 27, 2021
@cusxio cusxio changed the title __dirname is undefined import.meta.url returns relative path Aug 27, 2021
@cusxio
Copy link
Author

cusxio commented Aug 27, 2021

I've updated the issue.

@axe-me
Copy link
Owner

axe-me commented Aug 27, 2021

hi @cusxio , I just verified that in vite the import.meta.url does return a relative path. To convert a relative path to an absolute one you can do: path.resolve(import.meta.url)

@cusxio
Copy link
Author

cusxio commented Aug 28, 2021

So it seems that vite import.meta.url returns a different result from Node's.

In normal Node, import.meta.url returns file:///Users/x/Documents/test.ts.

So in vite, we'll need to use pathToFileURL.

The replicate __dirname in vite, dirname(fileURLToPath(pathToFileURL(import.meta.url)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants