Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@lit/ts-transformers

lit577BSD-3-Clause2.0.2TypeScript support: included

TypeScript transformers for Lit

readme

@lit/ts-transformers

Published on NPM Test status

TypeScript transformers for the Lit decorators.

Install

npm i @lit/ts-transformers

Transformers

idiomaticDecoratorsTransformer

import {idiomaticDecoratorsTransformer} from '@lit/ts-transformers';

Replaces all of the official Lit class and property decorators with idiomatic vanilla JavaScript.

Must run as a before transformer.

Example input

import {LitElement, html} from 'lit';
import {customElement, property} from 'lit/decorators.js';

@customElement('simple-greeting')
class SimpleGreeting extends LitElement {
  @property()
  name = 'World';

  render() {
    return html`<p>Hello ${this.name}!</p>`;
  }
}

Example output

import {LitElement, html} from 'lit';

class SimpleGreeting extends LitElement {
  static properties = {
    str: {},
  };

  constructor() {
    super();
    this.name = 'World';
  }

  render() {
    return html`Hello ${this.name}!`;
  }
}
customElements.define('simple-greeting', SimpleGreeting);

Supported decorators

Decorator Transformer behavior
@customElement Adds a customElements.define call
@property Adds an entry to static properties, and moves initializers to the constructor
@state Same as @property with {state: true}
@query Defines a getter that calls querySelector
@querySelectorAll Defines a getter that calls querySelectorAll
@queryAsync Defines an async getter that awaits updateComplete and then calls querySelector
@queryAssignedElements Defines a getter that calls querySelector('slot[name=foo]').assignedElements
@queryAssignedNodes Defines a getter that calls querySelector('slot[name=foo]').assignedNodes
@localized Adds an updateWhenLocaleChanges call to the constructor

preserveBlankLinesTransformer

import {
  preserveBlankLinesTransformer,
  BLANK_LINE_PLACEHOLDER_COMMENT,
  BLANK_LINE_PLACEHOLDER_COMMENT_REGEXP,
} from '@lit/ts-transformers';

A readability transformer that replaces blank lines in the original source with a special comment, because TypeScript does not otherwise preserve blank lines when it emits (see TypeScript#843).

The comment is always exactly:

//__BLANK_LINE_PLACEHOLDER_G1JVXUEBNCL6YN5NFE13MD1PT3H9OIHB__

Must run as a before transformer, and should usually placed in front of all other transformers.

constructorCleanupTransformer

import {constructorCleanupTransformer} from '@lit/ts-transformers';

A readability transformer that does the following:

  1. Moves constructors back to their original source position, or below the last static field if they are fully synthetic. By default, constructors will move to the top of a class whenever they are modified by TypeScript.

  2. Simplifies super(...) calls to super() in class constructors, unless the class has any super-classes with constructors that takes parameters according to the type-checker.

Must run as an after transformer.

Usage

There are a number of ways to compile a TypeScript program with transformers.

TypeScript compiler API

If you are using the TypeScript compiler API directly, pass the transformer to the customTransformers parameter of emit.

Example:

import ts from 'typescript';

import {
  idiomaticDecoratorsTransformer,
  preserveBlankLinesTransformer,
  constructorCleanupTransformer,
} from '@lit/ts-transformers';

// Note this is not a complete example. For more information see
// https://github.com/microsoft/TypeScript-wiki/blob/master/Using-the-Compiler-API.md
const program = ts.createProgram(...);
const result = program.emit(undefined, undefined, undefined, undefined, {
  before: [
    // Optionally preserve blank lines for better readability.
    preserveBlankLinesTransformer(),

    // Transform Lit decorators to idiomatic vanilla JavaScript.
    idiomaticLitDecoratorTransformer(program),
  ],
  after: [
    // Optional readability improvements for constructors.
    constructorCleanupTransformer(program),
  ],
});

ttypescript / ts-patch

ttypescript and ts-patch are two similar tools that augment the TypeScript compiler, adding the ability to declare transforms in your tsconfig.json.

Example:

{
  "compilerOptions": {
    "plugins": [
      {
        "transform": "@lit/ts-transformers",
        "import": "preserveBlankLinesTransformer"
      },
      {
        "transform": "@lit/ts-transformers",
        "import": "idiomaticDecoratorsTransformer"
      },
      {
        "transform": "@lit/ts-transformers",
        "import": "constructorCleanupTransformer",
        "after": true
      }
    ]
  }
}

If preserveBlankLinesTransformer is used, one way to remove blank line placeholder comments is with sed:

sed -i $'s/\s*\/\/__BLANK_LINE_PLACEHOLDER_G1JVXUEBNCL6YN5NFE13MD1PT3H9OIHB__/\\\n/g' lib/*.js lib/**/*.js

@rollup/plugin-typescript

@rollup/plugin-typescript is a Rollup plugin for compiling TypeScript that includes support for transformers.

Example:

import typescript from '@rollup/plugin-typescript';
import resolve from '@rollup/plugin-node-resolve';
import replace from '@rollup/plugin-replace';

import {
  idiomaticDecoratorsTransformer,
  preserveBlankLinesTransformer,
  constructorCleanupTransformer,
  BLANK_LINE_PLACEHOLDER_COMMENT,
} from '@lit/ts-transformers';

export default {
  input: './src/my-element.ts',
  plugins: [
    typescript({
      transformers: {
        before: [
          // Optionally preserve blank lines for better readability.
          {factory: preserveBlankLinesTransformer},

          // Transform Lit decorators to idiomatic vanilla JavaScript.
          {type: 'program', factory: idiomaticDecoratorsTransformer},
        ],
        after: [
          // Optional readability improvements for constructors.
          {type: 'program', factory: constructorCleanupTransformer},
        ],
      },
    }),

    // Only for when using preserveBlankLinesTransformer.
    replace({
      values: {
        [`//${BLANK_LINE_PLACEHOLDER_COMMENT}`]: '',
      },
      delimiters: ['', ''],
    }),

    resolve(),
  ],

  output: {
    file: 'dist/my-element.js',
    format: 'esm',
  },
};

changelog

Changelog

2.0.2

Patch Changes

  • #4907 01fa2942 Thanks @bennypowers! - Made typescript a peer dependency, this ensures that projects using a different version of typescript will get consistent results from this package.

2.0.1

Patch Changes

2.0.0

Major Changes

  • #3850 7e8491d4 - Remove transform for deprecated usage of queryAssignedNodes.

  • #4141 6b515e43 - Update TypeScript to ~5.2.0, which includes breaking changes to the TypeScript compiler APIs

2.0.0-pre.1

Major Changes

2.0.0-pre.0

Major Changes

  • #3850 7e8491d4 - Remove transform for deprecated usage of queryAssignedNodes.

  • #3814 23326c6b - Update to TypeScript 5.0, which includes breaking changes to the TypeScript compiler APIs.

Patch Changes

1.1.3

Patch Changes

1.1.2

Patch Changes

1.1.1

Patch Changes

1.1.0

Minor Changes

  • #2327 49ecf623 - Add queryAssignedElements decorator for a declarative API that calls HTMLSlotElement.assignedElements() on a specified slot. selector option allows filtering returned elements with a CSS selector.

Patch Changes

  • #2338 26e3fb7b - Deprecate @queryAssignedNodes API in preference for the new options object API which mirrors the @queryAssignedElements API. Update the documentation for both @queryAssignedNodes and @queryAssignedElements to better document the expected return type annotation.

1.0.2

Patch Changes

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

1.0.1

Fixed

  • Fixed Cannot read properties of undefined (reading 'elements') exception that would be thrown if a file imported a Lit decorator, and also included a default import from any package.

1.0.0

  • Initial release of @lit/ts-transformers.