Plotly import and require

requiring Plotly (commonjs) in observable works fine, even when presented as a esm module:

Plotly = require(“https://esm.sh/plotly.js@2.34.0”)

outside observablehq,

Plotly = (await import(“https://esm.sh/plotly.js@2.34.0”)).default

also works well

however, none of these work from within observablehq

Plotly = import(“https://esm.sh/plotly.js@2.34.0”)
Plotly = await import(“https://esm.sh/plotly.js@2.34.0”)
Plotly = (await import(“https://esm.sh/plotly.js@2.34.0”)).default

looking at the error messages, there appears to be a conflict between esm and commonjs in the way Plotly is packaged?

2 Likes

It’s an UMD loader conflict, likely caused by Plotly including the entire d3 meta package. Observable notebooks automatically include d3-require which registers itself at window.define.

If you run the following (disclaimer: not recommended),

Plotly = delete window.define, await import("https://esm.sh/plotly.js@2.34.0")

you can import Plotly successfully.

1 Like

thank you! This inspired a gentler version of your solution:

let Plotly
if(typeof(define)=='undefined'){
    Plotly = (await import("https://esm.sh/plotly.js@2.34.0")).default
}else{
    define(['https://cdn.plot.ly/plotly-2.34.0.min.js'],function(mod){Plotly=mod})
}

Can you share more context on what use case you’re optimizing for? I’m wondering why you wouldn’t just always use require, e.g.

require("plotly.js@2.34.0/dist/plotly.min.js")

sure, the context is an application where all dependencies are es6 modules and they need to be resolved with dynamic imports and can run both as vanilla JS and within observablehq notebooks. It turns out Plotly esm is not able to handle both environments (ref your comments above) so we need an implementation where import (es6) is handled as a require in observable. To the point, is there an import of a es6 module with a Plotly dependency that can be resolved both in vanila js and observable? Here’s a test, try this in both envs and confirm that it works:

seroHub = (await import(“https://episphere.github.io/serohub/serohub.mjs”)).seroHub

Fwiw, a while back I implemented a workaround to handle multiple d3-require instances:

1 Like