user11137806
user11137806

Reputation:

Web components, how to separate HTML from code

I would like to know if it is possible (I am using ES6 and Typescript) to separate my HTML code from my components i.e. include the HTML code into a variable from another file.

Currently we are writing all HTML within a structure like this:

let html = `<h1>Hello</h1> world!`

Which is obviously not cool when you have a lot of HTML.

Is there a way to separate my HTML from my Javascript component so I could do for example:

let html = include('index.html');

Upvotes: 2

Views: 1813

Answers (2)

Intervalia
Intervalia

Reputation: 10945

I created a tool to allow you to write your HTML as regular files and allow you, if you want it, to create translations that can be incorporated into each component.

It uses rollup to generate a compiled file that includes your JS, HTML, CSS and language info.

https://www.npmjs.com/package/component-build-tools

I am working on an upgrade that makes it simpler and does not require the combining of the files into one. I will adjust this answer once that is done.

Upvotes: 0

Supersharp
Supersharp

Reputation: 31181

You could use fetch(). It's an asynchronous function so you'll avec to use async/await or Promises.

class MyComponent extends HTMLElement {

    async connectedCallback() {
        let res = await fetch( 'my-component.html' )

        this.innerHTML = await res.text()
    }

}
customElements.define( 'my-component', MyComponent )

Upvotes: 6

Related Questions