在打字稿中导入html模板

雪熊

我正在尝试使用importhtml模板,以便Webpack能够识别它们并在构建时包括它们。webpack -d

根据这个GitHub问题,我应该这样做

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

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

但这并不能解决问题。

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模块更改为

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问题中的其他人似乎使它像这样工作。

费利克斯莫什

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

由于webpack是处理html导入的事实,因此默认情况下不会导出默认值。

但是你可以配置你的html-loader使用出口默认。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章