是否可以使用TypeScript将HTML文件导入为字符串?

问题描述 投票:24回答:2

我想知道是否有可能像标题所说的那样做。

例如,假设我们正在开发一个Angular2项目,我们希望避免将模板设置为外部URL,以减少http请求。我们仍然不想在组件中编写所有HTML,因为它可能足够大,或者我们希望设计人员使用不同于开发人员的文件。

所以这是第一个解决方案:

File template.html.ts将文件转换为.ts,如下所示:

export const htmlTemplate = `
   <h1>My Html</h1>
`;

然后在我的组件中我可以像这样导入它:

import { Component } from 'angular2/core';
import {RouteParams, RouterLink} from 'angular2/router';
import {htmlTemplate} from './template.html';

@Component({
  selector: 'home',
  directives: [RouterLink],
  template:  htmlTemplate,
})

实际上这很好用,但是你丢失了IDE HTML智能,所以这对于创建HTML模板的设计人员/ dev来说是不好的。

我想要实现的是找到一种方法来导入.html文件,而不是.ts。

那么可以在.TypeScript中将.html文件作为字符串导入吗?

javascript html import typescript angular
2个回答
13
投票

你现在可以这样做:

import "template.html";

@Component({
  selector: 'home',
  directives: [RouterLink],
  template:  require("template.html"),
})

这将包含“template.html”到组件的依赖项列表,然后您可以将它与您的构建器捆绑在一起(实际上,使用amd更有意义)

但是,正如你所建议的那样,最好使用webpack

看看这个starter pack


更新现在你可以像这样声明一个html模块:

declare module "*.html" {
    const content: string;
    export default content;
}

并像这样使用它:

import * as template from "template.html";

@Component({
  selector: 'home',
  directives: [RouterLink],
  template: template
})

1
投票

@ Veikedo上面的回答几乎有效;但是* as部分意味着整个模块被分配给指针template而我们只想要内容。编译器错误如下所示:

ERROR in /raid/projects/pulse/angular-components/src/lib/card/card.ts (143,12): Argument of type '{ moduleId: string; selector: string; template: typeof '*.html'; encapsulation: ViewEncapsulation...' is not assignable to parameter of type 'Component'.

更正后的import语句(在撰写本文时,使用TypeScript 2.3.3)如下:

import template from "template.html";

@Component({
  selector: 'home',
  directives: [RouterLink],
  template: template
})
© www.soinside.com 2019 - 2024. All rights reserved.