Importing distant modules in javascript from unpkg

Viewed 1326

I’m trying to import whole modules in a javascript file.

This file pertains to the Home Assistant environment where the frontend is written in javascript, usually using LitElements and modules (cf. documentation).

For instance, the doc uses a fancy wired-card by writing:

import "https://unpkg.com/wired-card@0.8.1/wired-card.js?module";.

I've read a lot about the import call but resources are usually about local elements and it seems that I need them to be distant.

In fact, I know the plain old JS quite well but I am a bit clueless regarding importing modules (and LitElements for that matter).

For instance, I'm looking for an accordion (expansion panel), like the one of JQueryUI. I found several resources (e.g. here, here, or here) but I couldn't find how to import them easily.

What makes a module importable? Are those not or am I doing it wrong?

1 Answers

In standard ECMAscript, a JS file is importable if it defines a module in the new system. Kinda circular.

Basically, it should export some resources from the module file. For example, if I have a test-module.js, I can export some class using the export keyword:

class Fubar {}

export { Fubar }

// or, more concisely

export class Fubar {}

The export keyword tells the module system that the resource defined should be made available to importers.

On the flip side, if you want to import a module, you must also do so from a module! This is because module imports are async and processed before the execution (excluding the dynamic import() function).

So, if I want to import my Fubar class from another module, I can do this:

import { Fubar } from './test-module.js`

However, if I load this script as a non-module, I will get an error. Instead, I must tell the browser that the script is a module:

<script type="module" src="test-module.js"></script>

So, in short, something is "importable" if it is itself a module.

More reading:

EDIT: something I missed - to make web resources a little nicer, the import URLs can be any URL, not just a relative path. This allows importing 3rd party scripts as modules. But, those 3rd party scripts need to be modules themselves.

Related