是否可以使用 TypeScript 将 HTML 文件作为字符串导入? [英] Is it possible to import an HTML file as a string with TypeScript?

查看:24
本文介绍了是否可以使用 TypeScript 将 HTML 文件作为字符串导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以按照标题所说的那样做.

I wonder if it is possible to do as the title said.

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

For example let's say we are working on a Angular2 project and we want to avoid set the template as an external url in order to have less http requests. Still we don't want to write all the HTML within the component because maybe it's big enough or we want designers to work in different files than devs.

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

So here is a first solution:

文件template.html.ts将文件转换为 .ts 格式如下:

File template.html.ts Transform a file to .ts to something like this:

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

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

Then in my component I can import it like this:

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 模板的设计人员/开发人员不利.

Actually this works perfectly but you are loosing the IDE HTML intelligence so this is bad for the designer/dev that creates the HTML templates.

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

What I'm trying to achieve is to find a way to import .html files and not .ts.

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

推荐答案

您现在可以这样做:

import "template.html";

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

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

this will include "template.html" to the dependencies list of your component and then you can bundle it with your builder (actually, it makes more sense with amd)

但是,正如您所建议的,最好使用 webpack.

However, as you were suggested, it's better to use webpack.

看看这个入门包

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

UPDATE now you can declare an html module like so:

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

并像这样使用它:

import * as template from "template.html";

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

这篇关于是否可以使用 TypeScript 将 HTML 文件作为字符串导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆