Import template from separate html file in polymer 3
Asked Answered
J

3

8

Instead of return "HTML CONTENT"; I have a separate html file and I want to import it to my js file to return the content of it but import template from '/m-chip.html"; does not work.

element.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>

How can I achieve this without jquery and plain js?

Jeromyjerreed answered 24/9, 2017 at 17:58 Comment(0)
S
3

Well importing html files is not something that javascript will understand at the moment. However you can build your project with webpack and add html-loader https://github.com/webpack-contrib/html-loader that specify how to treat your html import inside javascript.

Storms answered 16/10, 2017 at 10:52 Comment(0)
R
2

Actually for html where you don't need the reference adjusting, i export the html code as a string through the js module export default :

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

And in the polymer element i import the ES6 module eg:

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

It's not the best solution, but for the moment to made some tests with Polymer3 and templating structuring is not so bad !

Routh answered 24/11, 2017 at 16:29 Comment(0)
M
0

Try

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

...

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

and just plain html in the template html file, that works for me.

Mantilla answered 31/12, 2018 at 9:3 Comment(2)
It doesn't look like this works natively without the use of additional libraries. Chrome throws a MIME type error.Peewee
You definitely need a transpiler like Webpack to be able to pull this off.Tejeda

© 2022 - 2024 — McMap. All rights reserved.