javascriptweb-componentlit

TypeError: Module name, 'lit' does not resolve to a valid URL


I am trying out WebComponents for the first time and I am trying to use lit for it. It keeps showing this error

My HTML File

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./styles.css">
  <script type="module" src="app.js"></script>
  <title>Document</title>
</head>
<body>
  <payment-sdk></payment-sdk>
</body>
</html>
import {LitElement, html, css} from 'lit';

I have tried removing the module attribute from the HTML but it still didn't work. it now gave the error

javascript es6 import "expects exactly one argument"

I am also considering using Babel to compile it, but i do not think it would work since i am still getting errors I also added "type": "module" in my package,json file


Solution

  • You are using ESM for your dependency lit. When you use ESM in this way, you should provide an absolute paths for the imports.

    So, instead of simply doing import {} from "lit", you should the specify the absolute URL to it, like import {} from "../../node_modules/lit.index.js" (or what-ever is the right path)

    If you don't have the ESM copy of lit with yourself, alternatively you can use ESM CDNs like esm.sh. To use them, add the below script tag as the first child of your head tag

    <script type="importmap">
      {
        "imports": {
          "lit": "https://esm.sh/lit@3.1.1"
        }
      }
    </script>

    Here, we are telling browser to load lit from the URL that we have mapped it to