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

jsx-pistols

v0.5.1

Published

TypeScript and JSX as web templates, for NodeJS.

Downloads

57

Readme

JSX Pistols

JSX as web templates, tweaked for fast development. For TypeScript and NodeJS.

  • Hot reload in development mode
  • Native NodeJS require() in production mode
  • Freely import arbitrary sources & typings in your templates
  • Express support
  • Asynchronous rendering

Under the hood, this is just a thin wrapper for preact-render-to-string, using Babel for live transpiling during development.

Table of Contents

Installation

npm install jsx-pistols

Example

Template

import * as React from "preact";
import { MyControllerContext } from "./mycontroller";

export default function render(context: MyControllerContext) {
  return <html><body>Hello {context.name}!</body></html>;
}

In production, it is recommended to let TypeScript compile the templates to JavaScript for performance.

Rendering

Using the API

import JsxPistols from 'jsx-pistols';

const jsxPistols = new JsxPistols({ rootPath: 'path/to/templates' });
const result = await jsxPistols.render('mytemplate', { name: 'John' });

console.log(result); // <!doctype html><html><body>Hello John!</body></html>

Using an Express app

const app = express();

new JsxPistols({ expressApp: app });

app.set("view engine", "tsx"); // can be switched to "js" in production

app.get('/', (req, res) => {
  res.render('mytemplate', { name: 'John' })
})

API reference

Constructor

new JsxPistols([options: Object])

  • rootPath (string): The root path from which templates will be resolved. Defaults to the current working directory.
  • expressApp (object): An Express application that will be configured for using JSX Pistols as an engine. Extensions .js, .jsx and .tsx will be registered.
  • babelOptions (object): Options object to pass to the Babel transpiler. By default, the transpiler will support TypeScript and ECMAScript modules (see below).
  • prependDoctype (boolean): Whether to prepend "<!doctype html>" if the root element is an "<html>" tag. Defaults to true.
  • productionMode (boolean): Whether to import the templates as native JS modules. Defaults to true if NODE_ENV is set to 'production', false otherwise. If production mode is disabled, the library will compile the template on every render, and also prevent Node from caching code that is only imported in templates.

Methods

jsxPistols.render(templatePath: string[, context: any])

Renders a template file.

  • templatePath (string): Path to the template. Either absolute, or relative to the specified rootPath. Extension may be omitted if .jsx or .tsx.
  • context (any): Any context will be passed as the first parameter of the template rendering function.

jsxPistols.expressEngine(filePath: string, options: object, callback: Function)

Express-compatible templating engine. Can be used as an alternative to the expressApp constructor option, for finer control on Express configuration.

Template contract

The only requirement is that the default export must be a function returning a JSX element. Minimal example:

import * as React from "preact";

export default function render(context: any) {
  return <div></div>;
}

Note: while not necessarily a good practice, the render function can return a promise for asynchronous rendering.

Default Babel options

By default, the transpiler will support TypeScript and JSX. If you want different features to support, in order to match more closely your TypeScript config, you will need to override this object. The @babel/plugin-transform-modules-commonjs plugin is however mandatory, not keeping it will break all templates.

See also the Babel options reference.

{
  "presets": [[
    "@babel/preset-typescript",
    {
      "allExtensions": true,
      "isTSX": true
    }
  ]],
  "plugins": [
    "@babel/plugin-transform-modules-commonjs",
    "@babel/plugin-transform-react-jsx"
  ]
}

Tips and caveats

Your templates may have to work around some issues due to the nature of JSX.

  • class vs className

Prefer using Preact over React for your JSX typings, as the former accepts class as an attribute. Although both will be rendered properly.

  • Functions returing multiple tags

Use fragments:

function listElements() {
  return <>
    <li></li>
    <li></li>
    <li></li>
  </>;
}
  • Using handler attributes

Preact will not render React handlers like onClick. It will work fine though for the actual native handlers (onclick in lower case). You will have to extend your JSX definitions to make your compiler accept them, here is an example with Preact:

// types/preact/index.d.ts
// (to be referenced in tsconfig.json > compilerOptions > typeRoots)

import "preact";

declare module "preact" {
  namespace JSX {
    interface HTMLAttributes<RefType extends EventTarget = EventTarget>
        extends preact.ClassAttributes<RefType>, DOMAttributes<RefType> {
      onclick?: string;
    }
  }
}

License

MIT License

Copyright (c) 2020 Marwane Kalam-Alami