skypackjs / skypack-cdn

An issue tracker for the CDN
107 stars 5 forks source link

Example usage assumes a default export? #167

Open mbostock opened 3 years ago

mbostock commented 3 years ago

Some packages (e.g., d3-format) do not provide a default export; instead they provide named exports. These named imports can be imported individually or as a namespace with *. Yet Skypack doesn’t seem to detect whether a package has a default export and always recommends importing the default export even if none exists:

<script type="module">
  import d3Format from 'https://cdn.skypack.dev/d3-format';
</script>

This results in broken code since d3Format will be undefined. What we need instead is:

<script type="module">
  import * as d3Format from 'https://cdn.skypack.dev/d3-format';
</script>

Or perhaps better:

<script type="module">
  import {format} from 'https://cdn.skypack.dev/d3-format';
</script>

This problem extends to the “Open in CodePen” button, which directs users to CodePen with some broken default code.

Some possible options:

  1. Skypack could detect whether a package has a default export, and if it doesn’t, recommend importing as a namespace with * instead.
  2. Skypack could always recommend importing as a namespace (since you can still access the default export when you have the namespace, but the opposite is not true).
  3. Skypack could support some package.json metadata to allow package authors to specify what example code to show here. This shifts the burden to package authors, which isn’t ideal, but it’s better than the current situation and gives authors control over the example code shown to Skypack users.
drwpow commented 3 years ago

Those are all great suggestions, thank you. We agree that while the current code snippets work for most packages, they definitely break for some, and it’s not ideal. Especially for things like d3-format.

We had actually discussed #3—letting package authors control the import—but like you pointed out that won’t automatically provide good defaults for everyone.

In preparation for this we have started collecting more package info behind-the-scenes for the possibility of a better import. Let me see what we can do about a better snippet, at least an improvement from what’s there now.