49

I need to resolve ES modules, imported via static import or function-like dynamic import, in a way similar to how CJS modules in node.js can be resolved using require.resolve(). Does anything like that exist for ES modules?

For example, if a Vue package have both vue.runtime.common.js and vue.runtime.esm.js. I need to get path to vue.runtime.esm.js. If package doesn't have one, I'd like to know it.

thorn0
  • 9,362
  • 3
  • 68
  • 96
Dmitry Sharshakov
  • 678
  • 1
  • 6
  • 7
  • E.g. Vue package have both vue.runtime.common.js and vue.runtime.esm.js. I need path vue.runtime.esm.js one. If package doesn't have one, I'd like to know it. – Dmitry Sharshakov Mar 04 '19 at 06:37
  • Since ESM is agnostic as to package managers (e.g., the browser doesn't understand `import 'someNpmPackage'`), I don't think you will find an ES way. However, if you know what the path to the vue package will be relative to your module, you could use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import.meta – Brett Zamir Jun 07 '19 at 01:38

2 Answers2

58

As long as import.meta.resolve stays experimental, you can use createRequire to get back the require.resolve functionality in ES modules, e.g.

import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const pathName = require.resolve('vue.runtime.esm.js');
Adrian Macneil
  • 13,017
  • 5
  • 57
  • 70
GOTO 0
  • 42,323
  • 22
  • 125
  • 158
  • this requires a `tsconfig.json` with `{ "compilerOptions": { "module": "es2020" } }` ([via](https://stackoverflow.com/questions/70440505/ts1343-the-import-meta-meta-property-is-only-allowed-when-the-module-opti)) – milahu Apr 01 '22 at 10:51
  • 6
    @MilaNautikus This answer is actually for JavaScript, not TypeScript. – GOTO 0 Apr 01 '22 at 11:11
15

you can use import.meta.resolve()

here is an example from the node docs

(async () => {
  const dependencyAsset = await import.meta.resolve('component-lib/asset.js');
})();

note that you need to pass in --experimental-import-meta-resolve for this to work, as of node 14.3.0

hyperupcall
  • 869
  • 10
  • 21
  • 2
    this requires a `tsconfig.json` with `{ "compilerOptions": { "module": "es2020" } }` ([via](https://stackoverflow.com/questions/70440505/ts1343-the-import-meta-meta-property-is-only-allowed-when-the-module-opti)) – milahu Apr 01 '22 at 10:52
  • 2
    The flag `--experimental-import-meta-resolve` is still required today (`v19.6.1`). – brillout Feb 20 '23 at 12:54