Typescript: how to import .ts files as source string

This discussion assumes that typescript 2you can import an external non file cssas a string to be used in my class.

I am trying to use this to import HTML into my typescript component so that my application makes one HTTP request, getting the component and its HTML template instead of two separate requests. I tried:

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

The typescript compiler does not cause errors. However, when I launch the application, it is reset after a request http://localhost/textand receiving 404not found`

I also tried: 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 ?

+4
1

, Angular 2 rc.6

1 typescript 2, .

npm install typescript@2.0.2

2 system tsconfig.json

"compilerOptions": {
    "target": "ES5",
    "module": "system",
    ...
}

3 . , ; ...

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

...

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

4 typescript, __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 : main.ts

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

6 , . systemjs-plugin-:

npm install systemjs-plugin-text@0.0.9

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

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 , .

+4

Source: https://habr.com/ru/post/1654030/


All Articles