简体   繁体   中英

import html template in typescript

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM