Componentデコレータ
@Component() is a decorator that designates a TypeScript class as a Stencil component.
Every Stencil component gets transformed into a web component at build time.
import { Component } from '@stencil/core';
@Component({
tag: 'todo-list',
// additional options
})
export class TodoList {
// implementation omitted
}
Componentオプション
The @Component() decorator takes one argument, an object literal containing configuration options for the component.
This allows each component to be individually configured to suit the unique needs of each project.
Each option, its type, and whether it's required is described below.
tag
Required
Type: string
Details:
This value sets the name of the custom element that Stencil will generate.
To adhere to the HTML spec, the tag name must contain a dash ('-').
Ideally, the tag name is a globally unique value.
Having a globally unique value helps prevent naming collisions with the global CustomElementsRegistry, where all custom elements are defined.
It's recommended to choose a unique prefix for all your components within the same collection.
Example:
import { Component } from '@stencil/core';
@Component({
tag: 'todo-list',
})
export class TodoList {
// implementation omitted
}
After compilation, the component defined in TodoList can be used in HTML or another TSX file:
<!-- Here we use the component in an HTML file -->
<todo-list></todo-list>
{/* Here we use the component in a TSX file */}
<todo-list></todo-list>
assetsDirs
Optional
Type: string[]
Details:
assetsDirs is an array of relative paths from the component to a directory containing the static files (assets) the component requires.
Example:
Below is an example project's directory structure containing an example component and assets directory.
src/
└── components/
├── assets/
│ └── sunset.jpg
└── todo-list.tsx
Below, the todo-list component will correctly load the sunset.jpg image from the assets/ directory, using Stencil's getAssetPath().
import { Component, Prop, getAssetPath, h } from '@stencil/core';
@Component({
tag: 'todo-list',
// 1. assetsDirs lists the 'assets' directory as a relative (sibling)
// directory
assetsDirs: ['assets']
})
export class TodoList {
image = "sunset.jpg";
render() {
// 2. the asset path is retrieved relative to the asset base path to use in
// the <img> tag
const imageSrc = getAssetPath(`./assets/${this.image}`);
return <img src={imageSrc} />
}
}
In the example above, the following allows todo-list to display the provided asset:
- The
TodoList's@Component()decorator has theassetsDirsproperty, and lists the file's sibling directory,assets/. This will copy theassetsdirectory over to the distribution directory. - Stencil's
getAssetPath()is used to retrieve the path to the image to be used in the<img>tag
For more information on configuring assets, please see Stencil's Assets Guide