Do require.resolve for ES modules
Asked Answered
T

2

62

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.

Titty answered 4/3, 2019 at 6:33 Comment(2)
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.Titty
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 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Cottingham
M
76

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');
Music answered 21/6, 2020 at 13:52 Comment(3)
this requires a tsconfig.json with { "compilerOptions": { "module": "es2020" } } (via)Lectern
@MilaNautikus This answer is actually for JavaScript, not TypeScript.Music
A potential issue is that it picks package.json#exports["."].require instead of package.json#exports["."].import which may or may not be what you want.Patagium
C
20

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

Coryphaeus answered 8/6, 2020 at 23:10 Comment(4)
this requires a tsconfig.json with { "compilerOptions": { "module": "es2020" } } (via)Lectern
The flag --experimental-import-meta-resolve is still required today (v19.6.1).Patagium
It's now, since 20.6.0, available without any flags: nodejs.org/en/blog/release/…Patagium
But the argument parent (aka cwd) still requires a flag: nodejs.org/api/…Patagium

© 2022 - 2024 — McMap. All rights reserved.