0

I want my HTML code for my web component to be in its own file, and therefore I would import it into the JS for my web component. I know I can use the <link> tag to do this, but that's obsolete now. How can I make a web component while having the HTML be in its own file, similar to Angular components?

Currently, I use fetch to fetch it, but that requires me to convert it into a string, then attach it to the DOM, and isn't pleasant when having multiple components. It works for now but doesn't seem right.

I read, but forgot where, I can do something like this:

import * as template from "my-component.html";

I tried it but I received this error:

Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

Is there any normal way to import an HTML file?

AskYous
  • 4,332
  • 9
  • 46
  • 82
  • Some suggestions here that may work for you: https://stackoverflow.com/questions/6451169/load-html-template-with-javascript/44096230. The gist is using ajax to load the HTML into a hidden div. Can be done early in the page lifecycle. – jwatts1980 Nov 18 '19 at 03:32
  • Do you mean [Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components)? – Rob Nov 18 '19 at 03:33
  • @Rob yes. Is web-component the wrong tag? – AskYous Nov 18 '19 at 03:35
  • Well, that link may answer your questions but we cannot supply that as an answer because it's a third party site and not really an answer to your question. – Rob Nov 18 '19 at 03:37
  • Oh I've read through that before. It doesn't import html elements. It puts it in the parent DOM rather than its own file. – AskYous Nov 18 '19 at 03:38
  • Package your `fetch`, string conversion, and injection into a module so you can use it in a general purpose way. – Ouroborus Nov 18 '19 at 05:07

0 Answers0