Decorators are special functions that can modify the behavior of classes, class methods, and class fields. Lit uses decorators to provide declarative APIs for things like registering elements, reactive properties, and queries.
Decorators are a stage 2 proposal for addition to the ECMAScript standard, which means they're neither finalized nor implemented in browsers yet. Compilers like Babel and TypeScript provide support for proposed features like decorators by compiling them into standard JavaScript a browser can run.
Lit supplies a set of decorators that reduce the amount of boilerplate code you need to write when defining a component. For example, the @customElement and @property decorators make a basic element definition more compact:
@customElement('my-element')
exportclassMyElementextendsLitElement {
@property() greeting="Welcome";
@property() name="Sally";
@property({type: Boolean}) emphatic=true;
//...
}
The @customElement decorator defines a custom element, equivalent to calling:
customElements.define('my-element', MyElement);
The @property decorator declares a reactive property.
To reduce the amount of code needed to run the component, decorators can be imported individually into component code. All decorators are available at lit/decorators/<decorator-name>. For example,
To use decorators with TypeScript, enable the experimentalDecorators compiler option.
You should also ensure that the useDefineForClassFields setting is false. Note, this should only be required when the target is set to esnext or greater, but it's recommended to explicitly ensure this setting is false.
"experimentalDecorators": true,
"useDefineForClassFields": false,
Enabling emitDecoratorMetadata is not required and not recommended.
Currently the older legacy mode of Babel decorators is not supported, but this may change as Babel evolves. See the Babel documentation if you want to experiment.
The allowDeclareFields setting is generally not needed, but it can be useful if you want to define a reactive property without using a decorator. For example,
The current decorators stage 3 proposal does not directly address this issue, but it should be solved as the proposal evolves and matures.
When using decorators, transpiler settings for Babel and TypeScript must be configured correctly as shown in the sections above for TypeScript and Babel.