Search code examples
javascriptimportlit-html

JavaScript: I Can't import anything


How can I import lit-html in my code? I Have this codes:

the index.js file in js folder:

import { html } from "lit-html";
myDiv = html`
    <div>
        <a href="">Hello, Click Me!</a>
    </div>
`;
document.body.innerHTML += myDiv;

and the index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JS Tests</title>
</head>
<body>
    <script type="module" src="js/index.js"></script>
</body>
</html>

and I getting an Error like this:

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

Solution

  • You can try

    import {render, html } from "https://unpkg.com/lit-html@0.7.1/lit-html.js"
    

    HTML

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>JS Tests</title>
    </head>
    <body>
        <script type="module" src="js/index.js"></script>
    </body>
    </html>
    

    JS

    import {render, html } from "https://unpkg.com/lit-html@0.7.1/lit-html.js";
    const myDiv = html`
      <div>
        <a href="">Hello, Click Me!</a>
      </div>
    `;
    
    render(myDiv,document.body);
    

    Please note that if you are using modules on browser (like above),each import will make a network call. You can use some module bundlers like webpack to build a single JS file (with all dependencies) before you ship the code to browsers.