【问题标题】:import html template in typescript在打字稿中导入html模板
【发布时间】:2018-05-22 14:42:37
【问题描述】:

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

根据this GitHub issue我应该这样做

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

【问题讨论】:

    标签: angularjs typescript angular-routing webpack-3 typescript-2.5


    【解决方案1】:

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

    因为 webpack 是处理 html 的一个事实,默认情况下导入它 doesn't do 导出。

    但是你可以configure你的html-loader使用导出默认值。

    【讨论】:

    • 啊哈,所以这实际上是 webpack 问题而不是 typescript 问题。
    • 这不是问题 :] 配置问题。
    猜你喜欢
    • 2019-04-12
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-29
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多