import html template in typescript

你。 提交于 2019-12-07 16:38:00

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/47712892/import-html-template-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!