Do require.resolve for ES modules

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.

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 'module';

const require = createRequire(import.meta.url);
const pathName = require.resolve('vue.runtime.esm.js');

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

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Next.js: Router.push with state

Similar Posts