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

查看:42
本文介绍了在打字稿中导入 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'; 应该可以工作.

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

但是这有效"

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'; 你需要使用导出默认语法.

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天全站免登陆