Search code examples
javascriptecmascript-6polymervaadinweb-component

How to use vaadin-text-field in script module


I have tried to use vaadin-text-field in a script module, but it fails with the following message

Uncaught TypeError: Failed to resolve module specifier "@vaadin/vaadin-lumo-styles/color.js". Relative references must start with either "/", "./", or "../".

Now I know that "Bare" import specifiers aren't supported in ES6 But is there a way to make this work without hacking on the component's imports. I mean locally of course

Here is my code :

<!doctype html>
<html>
<head>
  <!-- Polyfills only needed for Firefox and Edge. -->
  <script src="node_modules/@webcomponents/webcomponentsjs/webcomponents-bundle.js"></script>
</head>
<body>

  <script type="module">
    import {PolymerElement, html} from './node_modules/@polymer/polymer/polymer-element.js';
    import './node_modules/@vaadin/vaadin-text-field/theme/lumo/vaadin-text-field.js';

    class MyElement extends PolymerElement {

      static get properties() { return { }}

      static get template() {
        return html`
          <vaadin-text-field></vaadin-text-field>
        `;
      }
    }

    customElements.define('my-element', MyElement);
  </script>

  <my-element></my-element>

</body>
</html>

Note: I am using server to serve the file not polymer CLI


Solution

  • I found that serving the file with polymer serve is the fastest way to solve the problem.

    According to Polymer's Documentation

    The browser accepts only one kind of module specifier in an import statement: a URL, which must be either fully-qualified, or a path starting with /, ./ or ../. This works fine for importing application-specific elements and modules:

    However, it's challenging when you're writing a reusable component, and you want to import a peer dependency installed using npm. The path may vary depending on how the components are installed. So Polymer supports the use of Node-style named import specifiers

    Where @polymer/polymer is the name of the npm package. (This style of specifier is sometimes called a "bare module specifier".)

    These module specifiers need to be transformed to paths before they're served to the browser. The Polymer CLI can transform them at build time, and the Polymer development server can transform them at runtime, so you can test code without a build step. Many third-party build tools, like WebPack and Rollup also support named modules.