Dmitry
Dmitry

Reputation: 13

Angular 2 and TypeScript. How to compile HTML templates?

So I have files *.ts and it is easy to understand how to compile into *.js using tsc. But a question is how to compile HTML templates which I use in *.ts files?

For example, this code appears after it is compiled and launched in HTML file:

<script id="__bs_script__">//<![CDATA[
    document.write("<script async src='/browser-sync/browser-sync-client.2.14.0.js'><\/script>".replace("HOST", location.hostname));
//]]></script>

Upvotes: 1

Views: 1553

Answers (1)

Andy-Delosdos
Andy-Delosdos

Reputation: 3720

You will need some sort of build system to import HTML before compiling your TS. One way is to use tools like webpack or systemjs to achieve this.

If you're using Webpack

You can use raw-loader to import HTML files as a string and inline them into your component's template.

Here's an example Webpack config (:

module: {
    loaders: [ 
      {
        test: /\.html$/,
        loader: 'raw-loader',
        include: /src/,
        exclude: [helpers.root('src/index.html')]
      }
    ]
}

Then, in your template you can use:

template: require('./template.name.html')

You can read more about raw-loader here: https://github.com/webpack/raw-loader

After the loader runs it will import the html and your template will end up inline inside the TS when it is transpiled. e.g. template: '<div>your imported html</div>

If you're using SystemJs

You can use the text plugin. Add it to your config using:

System.config({
  map: {
    text: 'path/to/text.js'
  }
});

Then import and inline your HTML into your component's template using:

template: require('./template.html!text');

You can read a bit more about the text plugin here: https://github.com/systemjs/plugin-text

Upvotes: 1

Related Questions