How to import .html fragment using es6 syntax in TypeScript

How to import an HTML template from a relative path as follows:

import customSelectHtml from "./custom-select.html!text"; 

The TypeScript compiler complains that it cannot find the module. I tried to create an external module definition, but it does not allow relative paths in module names. I am using SystemJS as a module loader.

+8
import ecmascript-6 typescript
source share
4 answers

It's impossible.

Due to the definition of module in typescript, and as far as I know in ES6 javascript ( import ). The module cannot be html. The general approach is to import a javascript module that exports a string containing html, css, whatever. But this is not importing a file with raw html.

You might want to look at html import , but that is completely different.

+2
source share

I do not use typescript, but I use ES6. May be useful for you.

The way I solve this is to declare pattern strings using `` quotes. This works great for me, I would love to know if anyone thinks this is a bad habit.

below snippet with Angular (- ui-router).

index.js

 var indexTemplate = ` <div> <h1>{{ Index page }}</h1> </div ` export {indexTemplate} 

config.js

 import { indexTemplate } from './index.js' function config($stateProvider){ $stateProvider.state('index', { url: '/', controller: 'indexController', template: indexTemplate }) } 

For completeness, this assumes that the indexController is defined elsewhere. In addition, this configuration function is exported to the place where the application is defined. But all this is not related to the issue.

+4
source share

You can import it using the require syntax

1) Create an app.d.ts file and require a definition so that typescript knows that this is a function. (you do not need to add any additional library, support for systemJs syntax)

 declare function require(params:string): any; 

2) Now you can import your html using var template = require ('./custom-select.html! Text')

I found it even better because you can use require inline

 var directive = { template: require('./custom-select.html!text'), scope: {} } 
+1
source share

I don't know about SystemJS, but this is possible with Webpack and html-loader

0
source share

All Articles