Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing CommonJS modules to an ESM syntax

I'm struggling to understand how to import CommonJS modules into an ESM syntax. I'm currently trying to work with the library url-metadata. url-metadata exposes a top-level export as a callable (which does not really conform to CommonJS, AFAIK):

const urlMetadata = require('url-metadata')
urlMetadata(URL, ...)

It's not possible to write:

import urlMetadata from 'urlMetadata'

since no default export is defined.

Instead, I have to write:

import * as urlMetadata from 'url-metadata'

Or:

import urlMetadata = require("url-metadata")

I tried to read up on module loading in Node but I'm still somewhat confused as to what is the correct way to do this and why.

like image 773
Xen_mar Avatar asked May 16 '26 09:05

Xen_mar


1 Answers

import urlMetadata from 'url-metadata';

is syntactic sugar for

import { default as urlMetadata } from 'url-metadata';

Either will work fine.

The value assigned to module.exports in a CommonJS module is the default export.

See the Node.js docs.

like image 71
MikeM Avatar answered May 18 '26 22:05

MikeM