npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

typesafe-templates

v1.3.0

Published

Template engine for writing compiler-checked templates in TypeScript by leveraging JSX to generate JavaScript code from TypeScript code files rather than text templates.

Downloads

136

Readme

typesafe-templates

CircleCI npm version semantic-release

Template engine for writing compiler-checked templates in TypeScript by leveraging JSX to generate JavaScript code from TypeScript code files rather than text templates.

Under the hood, typesafe-templates uses Babel to build an AST, which is then traversed to find and replace JSX nodes. Such a tool can be useful for pre-generating customized Javascript files that vary by user or for creating HTML templates using JSX rather than a syntax like Pug (some limitations apply).

Example

template.tsx

interface Message {
    name: string;
    lang: 'en' | 'es';
}

(function() {
    <$repeat items={$.messages}>
        {($: Message) => {
            <$if test={$.lang === 'en'}>
                console.log('Good morning' + <$string value={$.name} />);
            </$if>;
        	<$if test={$.lang === 'es'}>
                console.log('Bueños dias' + <$string value={$.name} />);
            </$if>;
        }}
    </$repeat>
})();

script.ts

import { renderFile } from 'typesafe-templates';

async function main() {
    const data: { messages: Message[] } = {
        messages: [
            { name: 'Alice', lang: 'en' },
            { name: 'Bob', lang: 'en' },
            { name: 'Dora', lang: 'es' },
            { name: 'Diego', lang: 'es' }
        ]
    };
    
    const { code } = await renderFile('./template.tsx', data);
    console.log(code);
}

main();

Output

(function() {
    console.log('Good morning, Alice');
    console.log('Good morning, Bob');
    console.log('Bueños dias, Dora');
    console.log('Bueños dias, Diego');
})();

Installation

npm install typesafe-templates

Use the --save-dev flag if you will be generating templates as part of a development task.

Usage

To work properly you will need to include a type definition for JSX elements that assigns JSX.Element to any.

declare namespace JSX {
    type Element = any;
}

As a convenience, the $ symbol is used to represent a parent type of a scope. However, any name can be used. Presently the library does not support deep properties. A reference like $.level1.level2.level3 may type-check correctly, but the proper value will not be injected into the template.

Elements

Control Elements

Control elements are similar to JavaScript control blocks. They wrap a block of code and control its output into the rendered code. In JSX terms, they require props.children to be defined.

Because JSX is used here as substitute JavaScript expressions, you will often need to include a semicolon after the tag as you would with a normal statement.

<$if test={} />

Controls whether the wrapped contents will appear in the output.

<$repeat items={} />

Repeats the wrapped contents for each item in items. For each copy, a new data scope is created and set to value of the current item.

The $repeat element expects the children prop to be a function or arrow function expression; however, this surrounding function will be removed in the final output.

Example:

<$repeat items={$.messages}>
    {($: Message) => {
    	console.log(<$string value={$.name}>)
    }}
</$repeat>

Injection Elements

<$boolean value={} />

Outputs a boolean literal.

<$expr code={} />

Takes in a string representing an expression, parses it into AST, and adds the resultant node into the output.

<$number value={} />

Outputs a numeric literal.

<$string value={} />

Outputs a string literal.

Limitations

Currently TypeScript treats all JSX elements as the same type (which can be changed but only to one collective type). Therefore elements, when used as values, are treated as any and will not show type errors unless you manually typecast the element. Refactoring signatures, however, will work when using TS tooling to rearrange arguments.

Example:

function print(str: string, num: number, bool: boolean) {}

print(<$string />, <$string />, <$string />); // Will not report type errors

print(<$string /> as string, <$string /> as string, <$string /> as string); // Will report type errors