2016-09-08 5 views
4

This discussiontypescript 2에 외부 클래스 인 css 파일을 내 클래스에서 사용할 문자열로 가져올 수 있음을 나타냅니다.Typescript : .ts 파일을 원시 문자열로 가져 오는 방법

내 typescript 구성 요소로 HTML을 가져 오기 위해이 응용 프로그램을 사용하여 두 개의 개별 요청 대신에 & 구성 요소를 가져 오는 HTTP 요청을 하나 만들려고합니다. 나는 시도했다 :

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가 나는 또한 시도했다

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 응답을받은 후 유골.

템플릿은 .ts 파일과 같은 폴더에 app.component.html입니다. 나는 typescript 2.0.2을 실행 중입니다. .html 템플릿과 .css 스타일 시트를 문자열로 가져 오려면 어떻게해야합니까? 여기

답변

4

당신이 이미하지 않은 경우 typescript 2을 설치 내 Angular 2 rc.6 응용 프로그램

1 위해, 그것을 한 방법이다. tsconfig.json

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

3에 컴파일러로 system

npm install [email protected] 

2 설정 모듈을 설정이 앱을 끊었다. 시스템 모듈을 사용하려면 edit every component을 수정하십시오. __moduleName 알 수 없기 때문에 타이프에 오류를 발생합니다 ...와

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

...

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

4이 교체합니다. 제거하려면 부트 스트랩 파일과 동일한 디렉토리에 사용자 정의 정의 파일 (.d.ts)을 만드십시오.

맞춤.main.ts

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

6 : 코드를 구문 분석 할 때 타이프 라이터가 그들을 볼 수 있도록 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는 부트 스트랩 파일에 입력 정의에 대한 참조를 추가 앱이 계속 실행되는지 확인합니다. 다음, install systemjs-plugin-text :

npm install [email protected] 

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 또는 이와 유사한 번들링 도구를 사용하면 외부 템플릿이 인라인됩니다.

관련 문제