【问题标题】:Typescript: how to import non .ts files as raw string打字稿:如何将非 .ts 文件作为原始字符串导入
【发布时间】:2017-01-16 14:10:43
【问题描述】:

This discussion 建议在typescript 2 中,可以将外部的非css 文件作为字符串导入我的班级。

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

typings.d.ts

declare module "*!text" {
    const value: any;
    export default value;
}

app.component.ts

import htmlTemplate from './app.component.html!text';
...
constructor(){console.log(htmlTemplate)}

打字稿编译器不会引发错误。但是,当我运行该应用程序时,它在请求 http://localhost/text 并获得 404 not found 后崩溃`

我也试过: typings.d.ts

declare module "*.html" {
    const value: any;
    export default value;
}

app.component.ts

import htmlTemplate from './app.component.html';
...
constructor(){console.log(htmlTemplate)}

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

模板位于app.component.html 中,与.ts 文件位于同一文件夹中。我正在运行typescript 2.0.2。如何将我的.html 模板和.css 样式表导入为字符串?

【问题讨论】:

    标签: typescript module


    【解决方案1】:

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

    1 如果您还没有安装typescript 2。设置为编译器

    npm install typescript@2.0.2
    

    2tsconfig.json

    中将模块设置为system
    "compilerOptions": {
        "target": "ES5",
        "module": "system",
        ...
    }
    

    3 这破坏了应用程序。修复,edit every component 使用系统模块;替换...

    @Component({
        module: moduleId,
        templateUrl: './app.component.html',
    })
    

    与...

    @Component({
        module: __moduleName,
        templateUrl: './app.component.html',
    })
    

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

    custom.typings.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"
    

    5 在引导文件中添加对类型化定义的引用,以便 typescript 在解析代码时看到它们:ma​​in.ts

    ///<reference path="./custom.typings.d.ts"/>
    

    6 确保应用仍在运行。接下来install systemjs-plugin-text

    npm install systemjs-plugin-text@0.0.9
    

    7systemjs.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'
        }
    });
    

    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!!
    })
    

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

    【讨论】:

      猜你喜欢
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-14
      • 2018-12-04
      相关资源
      最近更新 更多