Skip to content

Support TypeScript embedded in HTML files. #12874

@KeithHenry

Description

@KeithHenry

It would be very useful for TypeScript to be embedded in HTML files.

Problem

Newer browsers can use HTML imports to reduce the number of requests when loading components. This is used especially in custom elements and libraries that extend them (for instance Polymer).

For instance, suppose I have a custom element with CSS, HTML and script components. I add it to my page with a single statement:

<link rel="import" href="my-component.html">

Then my-component.html looks something like:

...
<template>
    <style>
        ...
    </style>
    <p>HTML content!</p>
</template>
<script>
    // Javascript to create custom element
</script>
...

This can be made to work with with TypeScript with <script src="typescript-output.js"> but that results in another server round trip and loses the bundling of CSS, HTML and script that makes the HTML import pattern so useful.

The output of the TS transpile should be included in the component HTML when presented to the user.

Solution

One way to do this would be to support a .tshtml file format (or possibly .tml or .ts.html).

This would behave in editors like HTML, but any <script> tags in the file would be TypeScript.

The Javascript emitter would produce a .html file with the contents of any <script> tags converted to the target JS version. Any content outside of <script> tags would be included unchanged.

This would be consistent pattern for users, anyone familiar with .tsx transpiling to .jsx or .cshtml in Razor should recognise the behaviour.

A file format like .ts.html would work with current HTML editors without any changes, but would also add risk for any projects that already had files with that naming format. Perhaps it could be combined with <script language="TypeScript"> tags to avoid that.

Risks

If TypeScript doesn't support being embedded in HTML one of two things are likely to happen for all projects that want to use the HTML import browser feature:

  1. Third party tools to post-process .ts output into .html files will emerge (they probably already have) or...
  2. These libraries and the people that use them just won't use TypeScript.

At the moment these are limited to a few fairly bleeding edge libraries, mostly those using custom elements, shadow DOM and the like. However I'd argue that these are exactly the sort of projects that we want to use TypeScript.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Out of ScopeThis idea sits outside of the TypeScript language design constraintsSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions