Inverse function of `import.meta.resolve`

131 views Asked by At

In node.js, import.meta.resolve takes a module specifier (for our purposes: a relative or absolute path, or a bare module specifier with an optional subpath) and returns a path on disk.

Is there a function that performs the inverse operation? Given an abspath to a file on disk, I want to "deresolve" it to a package export's relative path as referenced in the exports map

"exports": { 
  ".": "./bundle.js",
  "./": "./dist/"
}

Given ./dist/a.js, how to I get to ./a.js?

There are some constraints for my version of the problem which may help in implementing the solution:

  1. We can assume that the package is on disk
  2. We take disk paths relative to the package root as input.
  3. We already know the path to the package's package.json
  4. The TypeScript API is available
  5. We can require node.js 18.16+
0

There are 0 answers