seancdavis
seancdavis

Reputation: 2821

How to import external HTML files into a TypeScript class

I'm attempting to build a JavaScript package that is using Webpack to compile a TypeScript file and all its imports into a single JavaScript file.

The main goal with this package is to spit out HTML to any application consuming the package, following a given set of conditions.

At the moment, I have this working well by using template literals. But, ideally I would love to move the markup into separate HTML template files that can be imported and parsed by relevant TypeScript classes. I'm assuming the best way to handle this scenario is to have Webpack convert that HTML to JavaScript during the build.

Unfortunately, this package must be framework agnostic, and can't take advantage of Angular or React, or anything like that.

Is this possible and is it worth the effort? If so, what do I need to do?

Here's an exmaple of what I'm doing:

main.ts

import { Header } from './app/header';

(function(){
  new Header();
})();

header.html

export class Header {

  public el: any;

  constructor() {
    this.el = document.querySelectorAll('[data-header]')[0];
    this.el.className += 'header';

    this.render();
  }

  public render() {
    this.el.innerHTML += `
      <a href="#" class="navbar-brand logo">
        <svg viewBox="0 0 578 84" width="578" height="84">
          <use href="assets/svgs/logo-crds.svg#logo-crds"></use>
        </svg>
      </a>
    `;
  }
}

In this example, I'd like to move the template we see in the render() function into its own header.html file.

Upvotes: 2

Views: 9857

Answers (1)

Leone
Leone

Reputation: 3403

Why don't you try out html-loader

I successfully did what you are trying to accomplish. Here are the steps I took:

  1. Add the html-loader npm package dependency in your project using

    npm install --save-dev html-loader
    
  2. Add an entry in your webpack.config.js configuration file, in the loaders section:

    { test: /\.html$/, loader: 'html-loader' }
    
  3. Tell typescript how to recognize require imports. You can do this by adding the following code into a new .ts file:

    declare var require: {
        (path: string): any;
        <T>(path: string): T;
        (paths: string[], callback: (...modules: any[]) => void): void;
        ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void) => void;
    };
    
  4. Assuming you have an html template called template.html in your project's root directory, you can now have the following code in your main.ts source code, as:

    var x = require("./template.html");
    console.log(x);
    

Now in the console you should see (as I have) your template's html code.

You can look into the html-loader documentation for detailed configuration of the loader. I hope that helps.

Upvotes: 1

Related Questions