🏠 back to Observable

Using "import" with esm module exporting a default class fails

Using unpkg or github pages for an import of an individual class file within the repo/package fails.

See:

Example:
HelloModel = import(“https://unpkg.com/@redfish/agentscript@0.4.2/docs/models/HelloModel.js”)
…creates
▸Module {default: class HelloModel, Symbol(Symbol.toStringTag): “Module”}

Using this via: hello = new HelloModel() results in:
TypeError: HelloModel is not a constructor

Ditto using github pages … both in the notebook above.

What am I doing wrong? I’ve used exactly these imports within vanilla pages with no problems.
Example: http://backspaces.net/temp/d3/?hello

Possibly dynamic import(path) doesn’t work with default exports?

1 Like

Fixed: I needed to use the default value in the returned module:

hello = new HelloModel.default()

1 Like

Right; import(…) returns a Promise to a Module, not a Promise to its default export. If you only want the default export, you can say:

HelloModel = (await import("@redfish/agentscript@0.4.2/docs/models/HelloModel.js")).default

This post was very helpful in finding out how to hook into a Geodesy library. This particular library requires use of esm in order to get it to work on command line node —

To use the library from the command line:

import Utm, { LatLon, Dms } from 'geodesy/utm.js';
console.log(new LatLon( 33, -116)) # note the LatLon class is already in the namespace

But it was unclear on how to use in Observable. Based on this discussion, I could bring in all modules into the object geodesy, and then access that way.


Hook into a library that doesn’t have an index.js

geodesy = (await import("https://unpkg.com/geodesy@2.2.0/utm.js"))

// Be sure access the classes you want from the geodesy object

// "48.8583° N, 002.2945° E"
new geodesy.LatLon( 48.8583, 2.2945).toString()

// "48° 51′ 30″ N, 002° 17′ 40″ E"
new geodesy.LatLon( 48.8583, 2.2945).toString('dms')


See this in action: https://observablehq.com/@roblabs/map-grids-scales-in-svg#geodesy

Thanks for the discussion @ mike & @backspaces

1 Like