Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 407
Dmitry Sharshakov Avatar asked Mar 04 '19 06:03

Dmitry Sharshakov


2 Answers

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');
like image 190
GOTO 0 Avatar answered Nov 18 '22 22:11

GOTO 0


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

like image 22
Edwin Avatar answered Nov 18 '22 21:11

Edwin