8

而不是return "HTML CONTENT";我有一个单独的 html 文件,我想将它导入我的 js 文件以返回它的内容但import template from '/m-chip.html";不起作用。

元素.js

import {Element as PolymerElement} from '../node_modules/@polymer/polymer/polymer-element.js';
import template from '/m-chip.html';
export class Mchip extends PolymerElement{
    static get template() {
        return template;
    } 
    constructor() {
        super();
    }
} 
customElements.define("m-chip" ,Mchip)

m-chip.html

<style>
...
</style>

<div>...</div>

如果没有 jquery 和纯 js,我怎么能做到这一点?

4

3 回答 3

3

那么导入 html 文件目前还不是 javascript 能够理解的。但是,您可以使用 webpack 构建您的项目并添加 html-loader https://github.com/webpack-contrib/html-loader指定如何在 javascript 中处理您的 html 导入。

于 2017-10-16T10:52:36.450 回答
2

实际上对于不需要调整引用的html,我通过js模块导出默认将html代码导出为字符串:

// exports a constant 
export default `
  <style>
    ...
  </style>
  <div>
    ...
  </div> `

在聚合物元素中,我导入了 ES6 模块,例如:

import template from '../templates/template.js'
...
static get template() {
  return template;
}

这不是最好的解决方案,但目前使用 Polymer3 进行一些测试并且模板结构还不错!

于 2017-11-24T16:29:38.940 回答
0

尝试

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

...

static get template() { 
    return html([template]);
}

并且只是模板html文件中的纯html,这对我有用。

于 2018-12-31T09:03:01.590 回答