如何在脚本模块中使用 vaadin-text-field

How to use vaadin-text-field in script module

我曾尝试在脚本模块中使用 vaadin-text-field,但失败并显示以下消息

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

现在我知道 "Bare" 导入说明符在 ES6 中不受支持 但是有没有一种方法可以在不破坏组件导入的情况下完成这项工作。 我的意思当然是本地

这是我的代码:

<!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>

注意:我正在使用 server 来提供文件而不是 polymer CLI

我发现用 polymer serve 提供文件是解决问题的最快方法。

根据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.