【问题标题】:Polymer Build cannot find ES6 classes which are not Polymer ElementsPolymer Build 找不到不是 Polymer Elements 的 ES6 类
【发布时间】:2018-08-09 19:56:57
【问题描述】:

我们正在使用 Polymer 2 来构建应用程序。我们有源自 Polymer Elements 的 Web 组件和处理业务逻辑的纯 ES6 类。我们在 html 文件中定义了 ES6 类,并通过 html import 将它们导入到应该使用类的地方。

myclass.html

<script>
    class MyClass {

        constructor(){
            this.text = "MyClass";
        }

        getText(){
            return this.text;
        }
    }
</script>

我的应用程序.html

<link rel="import" href="../bower_components/polymer/polymer-element.html">

<link rel="import" href="myclass.html">

<dom-module id="my-app">
  <template>
    <div>{{text}}</div>
  </template>

  <script>
    class MyApp extends Polymer.Element {
      static get is() { return 'my-app'; }

      static get properties() {
        return {};
      }

      constructor(){
        super();
        var myObject = new MyClass();
        this.text = myObject.getText();
      }
    }

    window.customElements.define(MyApp.is, MyApp);
  </script>
</dom-module>

这与通过源提供的聚合物服务完美运行。

但是当我们进行 Polymer 构建并通过构建运行时,它会给出以下错误。

my-app.html:1 Uncaught ReferenceError: MyClass is not defined
    at new MyApp (my-app.html:1)
    at my-app.html:1

【问题讨论】:

  • 您是否尝试过(或者有什么理由不这样做)使用&lt;script type="text/javascript" src="myclass.js"&gt;&lt;/script&gt; 导入 JS?
  • 是的,我试过了。但是没有用
  • 要通过script标签使用它,首先你必须export类。
  • 但是 Polymer 2 不支持 ES6 模块。 Polymer 3 将支持它。那么可以导出类吗?
  • 导入带有script 标签的 .js 文件在 HTML 和 JS 诞生之初就可以使用。它不需要导出。 export 是 JS 中 import 语句所必需的。

标签: ecmascript-6 polymer polymer-2.x


【解决方案1】:

通过如下修改 MyClass 解决了这个问题。添加静态获取属性方法。

<script>
    class MyClass {

        constructor(){
            this.text = "MyClass";
    }

    static get properties() {
        return {
        };
    }

    getText(){
        return this.text;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 2016-10-30
    • 2016-04-12
    • 1970-01-01
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多