Можно ли разделить компонент Polymer 3 на отдельные файлы JavaScript, HTML и CSS? - PullRequest
0 голосов
/ 29 ноября 2018

Я пытаюсь разделить компонент Polymer 3 на отдельные файлы, например:

import { html, PolymerElement } from '@polymer/polymer/polymer-element';

export default class TestSplit extends PolymerElement {
  static get template() {
    return html`
      <style>
        p {
          color: blue;
        }
      </style>

      <p>Hello from component</p>
    `;
  }
}

customElements.define('test-split', TestSplit);

будет выглядеть примерно так:

index.js:

import { PolymerElement, html } from '@polymer/polymer/polymer-element';

import css from './style.css';
import template from './template.html';

export default class TestSplit extends PolymerElement {
  static get template() {
    return html`
      <style>${css}</style>
      ${template}
    `;
  }
}

customElements.define('test-split', TestSplit);

style.css:

p {         
  color: blue;          
}

template.html:

<p>Hello from component</p>

Edit1:

Я опробовал следующий код с теми же файлами template.html и style.css:

import-test.js:

import { html, PolymerElement } from '@polymer/polymer/polymer-element';
import CssHtmlLoader from './cssHtmlLoader';

export default class ImportTest extends PolymerElement {
  static get template() {
    let htmlTemplate = CssHtmlLoader.prototype.getHtmlTemplate('template.html');
      console.log(htmlTemplate)
      return htmlTemplate.then(function (file) {
        return html`
          <link rel="stylesheet" href="style.css"> 
          ${file}
        `;
      });  
    }
  }
}

customElements.define('import-test', ImportTest);

Я получаю правильный файл из обещания: enter image description here

Но я также получаю следующие ошибки: enter image description here

Есть идеи, что не так с кодом?

Ответы [ 2 ]

0 голосов
/ 04 декабря 2018

Итак, я попробовал следующий компонент:

import-test.js

import { html, PolymerElement } from '@polymer/polymer/polymer-element';
import {htmlLiteral} from '@polymer/polymer/lib/utils/html-tag.js';
import CssHtmlLoader from './cssHtmlLoader';

export default class ImportTest extends PolymerElement {

  static get properties() {
    return {
      htmlTemplate:{
        type:String,
        notify:true,
        reflectToAttribute: true
      },
      helloWorld:{
        type:String,
        notify:true,
        reflectToAttribute: true,
        value: 'auto'
      }
    }
  }

  constructor(){
    super();
    var that = this;
    this.attachShadow({mode: 'open'});
    console.log(this.shadowRoot);
    this.htmlTemplate = CssHtmlLoader.prototype.getHtmlTemplate('templaten.html');
    this.htmlTemplate.then((template) => {
      console.log(that);
      that.shadowRoot.innerHTML = template
    });
  }
}

customElements.define('import-test', ImportTest);

со следующим шаблоном html и css:

style.css:

p {
    color: blue;
}

template.html:

 link rel="stylesheet" href="style.css"> 
 <p>Hello from template [[helloWorld]]</p>

и это был мой вывод:

Hello PolymerImportTest-app!
Hello from template [[helloWorld]](this is blue so the css import works)

поэтому моя проблема заключалась в том, что я не смог привязать свойства к html-шаблону.

И решение этой проблемы заключалось в том, чтобы поместить html-шаблон в отдельный файл javascript, и оттуда я смог экспортироватьи используйте его в пользовательском компоненте (с работающей привязкой свойств).

Вот мое решение:

import-test.js:

import { html, PolymerElement } from '@polymer/polymer/polymer-element';
import {template} from './template';

export default class ImportTest extends PolymerElement {

  static get properties() {
    return {
      helloWorld:{
        type:String,
        notify:true,
        reflectToAttribute: true,
        value: 'auto'
      }
    }
  }

  constructor(){
    super();
  }

  static get template() {
    return template;
  }

}

customElements.define('import-test', ImportTest);

template.js:

import {html} from '@polymer/polymer/polymer-element';

export const template=html`
<link rel="stylesheet" href="/src/PolymerImportTest-app/style.css">
<p>Hello from template [[helloWorld]]</p>
`;

style.css:

p {
    color: blue;
}

И вывод:

Hello PolymerImportTest-app!
Hello from template auto(blue and the property is correctly attached)
0 голосов
/ 29 ноября 2018

Я думаю, то, как вы хотите импортировать файлы CSS и HTML, невозможно.Это простые файлы CSS / HTML.Они не предоставляют никаких модулей для экспорта этих файлов.

Могут быть импортированы только экспортированные модули javascript.

Я не думаю, что есть какой-либо способ импортировать файл css в js:

import css from './style.css'; // css can't be imported this way.

Вместо этого Вы можете создать сервис для получения следующих файлов:

Допустим,

Обновлено:

------------------------------------------------------------ Рабочая копия ------------------------------------------------------------------

template.service.js :

export class TemplateService {

  xhrCall(url) {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.onload = () => resolve(xhr.responseText);
      xhr.onerror = () => reject(xhr.statusText);
      xhr.send();
    });
  }
  // As of now css is not dynamically included
  /*
  getCssTemplate(url) {
    return this.xhrCall(url);
  }
  */
  getHtmlTemplate(url) {
    return this.xhrCall(url);
  }

}

my-view1.html :

<div class="card">
  <div class="circle">1</div>
  <h1>View One</h1>
  <p>Ut labores minimum atomorum pro. Laudem tibique ut has.</p>
  <p>Lorem ipsum dolor sit amet, per in nusquam nominavi periculis, sit elit oportere ea.Lorem ipsum dolor sit amet, per in nusquam nominavi periculis, sit elit oportere ea.Cu mei vide viris gloriatur, at populo eripuit sit.</p>
</div>

my-view.html :

import { PolymerElement, html } from '@polymer/polymer/polymer-element.js';
import './shared-styles.js';

import { TemplateService } from './services/template.service.js';

class MyView1 extends PolymerElement {

  constructor() {
    super();
    this.tpl = new TemplateService();
    this.getView();  // <---------------call getView in the constructor.
  }

  static get template() {
    return html `<style include="shared-styles">
    :host {
      display: block;
      padding: 10px;
    }
    </style>
    `;
  }

  getView() {
    let template$ = this.tpl.getHtmlTemplate('src/templates/html/my-view1.html');
    // get the promise in a var above.
    template$.then(file => {
      let wrapperDiv = document.createElement('div'); // create a node
      wrapperDiv.innerHTML = file; // push the contents

      this._attachDom(wrapperDiv); // Attach the DOM to component's custom element**
    });
  }

}
window.customElements.define('my-view1', MyView1);
...