Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript modules - moving from <script> to "import ..." can't be done for some libs?

I was out of the loop when JavaScript got all fancy - I'm used to a <script src="https://somecdn/stuff.js"></script>, unsure about the package.json file, and have almost no experience with module packaging.

Sometimes I can move from a <script src="..." to import {functions} from 'https://somecdn/stuff.mjs'; without an issue. But other times it doesn't work.

Can everything be loaded through the new import statement, or are some scripts so module-unfriendly that I shouldn't bother?

To make it easier

  1. I'm only on latest Chrome
  2. My main script has the module tag: <script type="module" src="js/main.js"></script>

Successfully moved from script tag to import:

import {clear, del, get, keys, set} from 'https://cdn.jsdelivr.net/npm/idb-keyval@3/dist/idb-keyval.mjs';

But when I try to migrate

<script src="https://cdnjs.cloudflare.com/ajax/libs/dexie/3.0.0-alpha.6/dexie.js"></script>

it throws

Uncaught SyntaxError: The requested module 'https://cdnjs.cloudflare.com/ajax/libs/dexie/3.0.0-alpha.6/dexie.js' does not provide an export named 'default'

I'm assuming the "mjs" isn't the issue, as long as everything is being served as the right JS mimetype.

like image 408
Benjamin H Avatar asked Oct 20 '25 14:10

Benjamin H


1 Answers

You can only import things from files that export them.

https://cdnjs.cloudflare.com/ajax/libs/dexie/3.0.0-alpha.6/dexie.js seems to only be exporting anything (by assigning to module.exports) when running in an environment where module is defined (i.e. Node).

When run in the browser, it just adds Dexie to the global object, without exporting anything.

like image 163
ack_inc Avatar answered Oct 22 '25 05:10

ack_inc