2016-04-15 35 views
19

我想知道是否可以像標題所說的那樣做。是否可以使用TypeScript將HTML文件作爲字符串導入?

例如,假設我們正在開發一個Angular2項目,並且我們希望避免將模板設置爲外部url,以減少http請求。我們仍然不想在組件中編寫所有的HTML,因爲它可能足夠大,或者我們希望設計人員使用不同於開發人員的文件工作。

所以這是第一個解決方案:

文件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文件作爲字符串導入?

+0

我做了什麼來實現這一目標是在webpack中使用'require',創建一個html文件,然後使用'template:require('component.html')',它將作爲一個字符串導入。 –

+0

是的,這是一種方法。感謝你的加入,我也會和你一起玩,我會讓你知道我的想法。 –

+0

不是你正在尋找的解決方案,我使用gulp-angular-embed-templates在構建時在我的js類中嵌入html模板 – brando

回答

8

現在你可以這樣做:

import "template.html"; 

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

這將包括「template.html」你的組件的依賴關係列表,然後你可以用你的建設者(實際上,它使更多的意義將其捆綁amd

但是,正如您所建議的那樣,最好使用webpack

看看這個starter pack


UPDATE現在你可以聲明html模塊,像這樣:

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

,並使用它,像這樣:

import * as template from "template.html"; 

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

出於某種原因,我不認爲這是正確的。導入&需要該文件似乎很奇怪並且不正確。儘管感謝您的回答,我也會對其進行測試。 –

+0

我然後得到「無法找到模塊X」的錯誤。這個答案針對哪個版本的打字稿? –

+1

@BryanRayner在這裏看到https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#wildcard-character-in-module-names – Veikedo

-1

@ Veikedo的答案高於alm ost作品;然而* 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語句(在寫作的時候,使用打字稿2.3.3)如下:

import template from "template.html"; 

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