在打字稿中导入html模板 [英] import html template in typescript

查看:120
本文介绍了在打字稿中导入html模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试import我的html模板,以便Webpack能够识别它们并在构建时包含它们. (webpack -d)

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

根据此GitHub问题我应该这样做

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

然后import template from './myTemplate.html';应该可以工作.

但是并不能完全解决问题.

But it doesn't quite do the trick.

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

但是这个有效"

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

很奇怪.

但是现在这不起作用

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

但是,如果我将* .html模块更改为

However if I change my *.html module to

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

我现在可以做

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

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

它有效,但是为什么import template from './myTemplate.html';不起作用? 我在做什么错,因为GitHub问题中的其他人似乎都可以使它正常工作.

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.

推荐答案

您没有做错任何事情,要使用import template from './myTemplate.html';,您需要使用export default语法.

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

由于webpack是处理html的事实,因此将其导入

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

但是您可以配置您的html-loader以使用导出默认设置

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

这篇关于在打字稿中导入html模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆