2017-03-16 101 views
1

我在导入我的angular 2应用程序中的html模板时遇到了麻烦。Typescript 2通配符模块

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

在app.component.ts

import { Component } from '@angular/core'; 

import './app.component.css'; 
import * as template from './app.component.html'; 

@Component({ 
    selector: 'app', 
    template: <string>template 
}) 
export class AppComponent { 
    constructor() { 
     console.log('I am App'); 
    } 
} 

该应用的工作原理和模板加载globals.d.ts但我得到这个错误TS2352:类型“typeof运算“* .html“'不能转换为'string'类型。有人有解决方法吗?

我想这样做。

import template from './app.component.html'; 

@Component({ 
    template: template 
}) 
... 

但是编译后的代码就这样结束了。

var app_component_html_1 = __webpack_require__(653); 
... 
template: app_component_html_1.default 

app_component_html_1是我需要的字符串。为什么他们添加.default?

+1

你为什么这么做?为什么不只是'templateUrl:'。/ app.component.html''? – jonrsharpe

+0

正在测试角2 a,并使用templateUrl。但发现它很难用于webpack。需要额外的装载机和步骤来使其工作。 我以为只使用模板:会更容易。 xD –

+0

只是想说明我在TS 2.2中遇到同样的问题。但是,我的html导入使用ng-cache-loader和webpack解析为模板缓存键。我有从'./header.template.html';'import *作为templateUrl,但是当我去使用'templateUrl: templateUrl'指定一个指令时,我得到了与OP所述的相同的错误。 –

回答

4

修改export default content;export = content;解决了此打字稿错误。

之前 Not work

Worked

而且transpiled代码应该相应地工作(因为 '默认' 被移除)。

+0

刚刚对前一个添加了评论。我解释这一点对我来说不再是一个问题。不过谢谢你。也许别人觉得这很有用。 –

+0

我不知道这是为什么起作用,并且感觉像一个bug,因为我在TS git问题中看到的大多数评论都使用默认值。不过,这是我现在要做的。谢谢。 –

+1

我认为这是设计 - 因为'export ='是在Typescript文档中定义的有效表达式。 https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require – Val