简体   繁体   English

在typescript中导入html模板

[英]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. 我正在尝试import我的html模板,以便webpack能够识别它们并在构建时包含它们。 ( webpack -d ) webpack -d

According to this GitHub issue I should do this 根据这个GitHub问题,我应该这样做

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

Then import template from './myTemplate.html'; 然后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 但是,如果我将* .html模块更改为

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'; 它有效,但为什么不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. 我在做什么错,因为GitHub问题中的其他人似乎让它像那样工作。

You are not doing anything wrong, in order to use import template from './myTemplate.html'; 你没有做错什么,为了使用import template from './myTemplate.html'; you need to use export default syntax. 您需要使用export default语法。

Because of the fact that webpack is the one that handles html imports it doesn't do export default by default. 由于webpack是处理html导入的那个,因此默认情况下不会导出默认值。

But you can configure your html-loader to use export default. 但是您可以将html-loader 配置为使用export default。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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