打字稿:如何将非.ts文件导入为原始字符串

Bee*_*ice 5 module typescript

此讨论表明,typescript 2可以将外部非css文件作为字符串导入到我的类中.

我正在尝试利用这个将HTML导入到我的typescript组件中,这样我的应用程序就会发出一个HTTP请求来获取组件及其HTML模板而不是两个单独的请求.我试过了:

typings.d.ts

declare module "*!text" {
    const value: any;
    export default value;
}
Run Code Online (Sandbox Code Playgroud)

app.component.ts

import htmlTemplate from './app.component.html!text';
...
constructor(){console.log(htmlTemplate)}
Run Code Online (Sandbox Code Playgroud)

typescript编译器不会引发错误.但是,当我运行应用程序时,它会在请求http://localhost/text并找到404未找到的应用程序后崩溃

我也尝试过: typings.d.ts

declare module "*.html" {
    const value: any;
    export default value;
}
Run Code Online (Sandbox Code Playgroud)

app.component.ts

import htmlTemplate from './app.component.html';
...
constructor(){console.log(htmlTemplate)}
Run Code Online (Sandbox Code Playgroud)

同样在编译期间不会引发错误,但应用http://localhost/app.component.html.js程序在收到404 not found响应后请求并崩溃.

模板位于app.component.html文件所在的.ts文件夹中.我跑typescript 2.0.2.如何将.html模板和.css样式表导入为字符串?

Bee*_*ice 3

Angular 2 rc.6对于我的应用程序,我是这样做的

1typescript 2如果尚未安装,请安装。将其设置为编译器

npm install typescript@2.0.2
Run Code Online (Sandbox Code Playgroud)

2systemtsconfig.json中设置模块

"compilerOptions": {
    "target": "ES5",
    "module": "system",
    ...
}
Run Code Online (Sandbox Code Playgroud)

3这破坏了应用程序。要修复,请编辑每个组件以使用系统模块;代替...

@Component({
    module: moduleId,
    templateUrl: './app.component.html',
})
Run Code Online (Sandbox Code Playgroud)

和...

@Component({
    module: __moduleName,
    templateUrl: './app.component.html',
})
Run Code Online (Sandbox Code Playgroud)

4这会在打字稿中引发错误,因为__moduleName未知。要摆脱它,请.d.ts在与引导文件相同的目录中创建自定义文件 ( )。

自定义类型.d.ts

/** So typescript recognizes this variable wherever we use it */
declare var __moduleName: string;

/** Will be needed later to import files as text without raising errors */
declare module "*!text"
Run Code Online (Sandbox Code Playgroud)

5在引导文件中添加对类型定义的引用,以便打字稿在解析代码时看到它们:main.ts

///<reference path="./custom.typings.d.ts"/>
Run Code Online (Sandbox Code Playgroud)

6确保应用程序仍在运行。接下来,安装 systemjs-plugin-text

npm install systemjs-plugin-text@0.0.9
Run Code Online (Sandbox Code Playgroud)

7在systemjs.config.js中将新插件设置为地图

System.config({
    map:{
        'app':        'app',
        '@angular':   'node_modules/@angular',
        //'text' map is used to import files as raw strings
        text:         'node_modules/systemjs-plugin-text/text.js'
    }
});
Run Code Online (Sandbox Code Playgroud)

8现在我们已经准备好将文件作为字符串导入

// this line should raise no error if steps 4 & 5 were completed correctly
import htmlTemplate from './app.component.html!text';
console.log(htmlTemplate); //will print the file as a string in console

@Component({
    moduleId: __moduleName,
    template: htmlTemplate, //success!!
})
Run Code Online (Sandbox Code Playgroud)

就是这样!现在,如果您使用systemjs-builder或类似的捆绑工具,外部模板将被内联。