import html template in typescript

Snæbjørn picture Snæbjørn · Dec 8, 2017 · Viewed 9k times · Source

I'm trying to import my html template so that webpack will recognize them and include them when I build. (webpack -d)

According to this GitHub issue I should do this

declare module '*.html' {
    const _: string;
    export default _;
}

Then import template from './myTemplate.html'; should work.

But it doesn't quite do the trick.

import template from './myTemplate.html';
console.log(template); // undefined

However this "works"

import * as template from './myTemplate.html';
console.log(template); // <p>Hello world!</p>

Very strange.

But now this doesn't work

$routeProvider.when("/test", {
    template: template, // ERROR! template is typeof(*.html) expected string
    controller: MyController,
    controllerAs: "$ctrl"
});

However if I change my *.html module to

declare module '*.html' {
    const _: string;
    export = _; // changed this
}

I can now do

import * as template from './myTemplate.html';

$routeProvider.when("/test", {
    template: template, // Great success!
    controller: MyController,
    controllerAs: "$ctrl"
});

It works, but why doesn't import template from './myTemplate.html'; work? What am I doing wrong as the others in the GitHub issue seemed to get it to work like that.

Answer

felixmosh picture felixmosh · Dec 8, 2017

You are not doing anything wrong, in order to use import template from './myTemplate.html'; you need to use export default syntax.

Because of the fact that webpack is the one that handles html imports it doesn't do export default by default.

But you can configure your html-loader to use export default.