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 ?
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)
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.
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.
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.
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).
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With