Search code examples
javascriptnpmwebpackweb-componentes6-modules

Failed to resolve module specifier when using a Web Component


I have installed @tokens-studio/configurator package from NPM. However when I import it as suggested, I get the error:

Failed to resolve module specifier "@tokens-studio/configurator". 
Relative references must start with either "/", "./", or "../".

Here is my HTML file that imports the package:

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type="module">
      import '@tokens-studio/configurator';
    </script>
</head>

<body>
    <main>
        <configurator-element>
            <div style="height: 100%" slot="monaco-config"></div>
            <div style="height: 100%" slot="monaco-output"></div>
        </configurator-element>
    </main>
</body>

Any idea what I'm doing wrong?


Solution

  • Looks like you are trying to use ESM directly from browser without any bundling step. There are three types of imports:

    1. Absolute imports: import 'https://example.com/shapes/circle.js'
    2. Relative imports: import './circle.js'
    3. Bare imports: import '@tokens-studio/configurator';

    If you are familiar with Node.js, then all three are supported. For bare imports like the one you are using, Node.js looks at the node_modules directory starting from the current directory, all the way up to root directory.

    However, in browser land, the notion of bare import doesn't make any sense. Browser doesn't know where it should look for this particular module as it doesn't have access to native operating system.

    This is where the import-maps comes in. All the browsers now support it and it is defined here. You can define it like this (The actual path may change depending on your server and the main/export defined by the package.json file of @tokens-stuido/configurator pacakge):

    <script type="importmap">
      {
        "imports": {
          "@tokens-studio/configurator": "http://localhost:8080/node_modules/@tokens-studio/configurator/index.js",
        }
      }
    </script>
    

    You will also need to have some sort of server that can supply this required file from node_modules.

    The second option which is more common is to simply use a module bundles like Webpack, Vite or Parcel.