Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use ES Modules library from CDN?

I want to use this library via CDN.
https://www.jsdelivr.com/package/npm/lit-element

My js code is here.

import { LitElement, html } from "https://cdn.jsdelivr.net/npm/[email protected]/lit-element.js";

class MyElement extends LitElement {
    render(){
        return html`ABCD`
    }
}

customElements.define("my-element", MyElement)

I get following error.

Uncaught TypeError: Failed to resolve module specifier "lit-html". Relative references must start with either "/", "./", or "../".

Do I have to build using npm ?


Update

Following code works.

import { LitElement, html } from "https://unpkg.com/lit-element/lit-element.js?module"

class MyElement extends LitElement {
    render(){
        return html`ABCD`
    }
}

customElements.define("my-element", MyElement)
like image 943
blz Avatar asked Jun 08 '19 11:06

blz


People also ask

How can ECMAScript modules be used natively?

Enabling# Node.js has two module systems: CommonJS modules and ECMAScript modules. Authors can tell Node.js to use the ECMAScript modules loader via the .mjs file extension, the package.json "type" field, or the --input-type flag. Outside of those cases, Node.js will use the CommonJS module loader.

Can we use CDN for JavaScript?

CDNs are used widely for delivering stylesheets and JavaScript files (static assets) of libraries like Bootstrap, jQuery etc. Using CDN for those library files is preferable for a number of reasons: Serving libraries' static assets over CDN lowers the request burden on an organization's own servers.

Does node support ES module?

JavaScript uses the ECMAScript module (or ES module) to create packages for reuse. Besides the CommonJS module, Node. js supports ES modules in version 14.0.

How do you convert CommonJS module to ES module?

It is logically the same as: const init = require('./app/routes/routes'); init(app); So, to translate this to ESM, you change your routes module to export a named function. You can then import that named function and then call it (pass app to it).


1 Answers

Inside LitHtml and LitElement modules use bare module specifiers internally to import dependencies, and these aren't supported by JS modules yet. LitElement has import { TemplateResult } from 'lit-html', but JS needs that 'lit-html' replaced with whatever path to the actual file (not the abstract name of the package).

If you use the npm packages (which cdn.jsdelivr.net is serving up here) you have to use a build step (WebPack, Rollup, etc) to resolve all those import statements to either the file paths JS supports or inline all the files together.

The former is what unpkg.com ... ?module does, it replaces the bare reference to lit-html with the absolute https://unpkg.com/lit-html@^1.1.1/lit-html.js?module.

like image 112
Keith Avatar answered Sep 28 '22 17:09

Keith