Stencil中嵌套组件如何工作?为何子组件无需引入即可使用?
my-embedded-component be used directly in my-parent-component without importing it? I came across the following code snippets in the Stencil official docs and can't understand why my-embedded-component can be used directly in my-parent-component without providing the sub-component's path. Could someone explain this concept to me?
Child Component Code
import { Component, Prop } from '@stencil/core'; @Component({ tag: 'my-embedded-component' }) export class MyEmbeddedComponent { @Prop() color: string = 'blue'; render() { return ( <div>My favorite color is {this.color}</div> ); } }
Parent Component Code
import { Component } from '@stencil/core'; @Component({ tag: 'my-parent-component' }) export class MyParentComponent { render() { return ( <div> <my-embedded-component color="red"></my-embedded-component> </div> ); } }
Great question! This is one of Stencil's built-in conveniences that simplifies component composition. Let's break down why this works:
Stencil's Compiler Automatically Registers Components
When you build your Stencil project, the compiler scans every component file (marked with the@Componentdecorator) and automatically registers their custom element tags with the browser's Custom Elements API. After building, every component in your library becomes available as a native HTML element throughout your app—no need to manually import them into every parent component that uses them.Type Safety Without Explicit Imports
Even though you don't importmy-embedded-componentin the parent component, Stencil's TypeScript plugin still ensures type safety for the component's props (like thecolorprop here). The compiler generates type definitions for all your components, so you get autocomplete and validation just as if you'd imported the component class directly.Web Component Standards at Play
Fundamentally, Stencil components are standard web components (Custom Elements). Once a custom element is defined in the browser (which Stencil handles during build and app bootstrapping), you can use its tag name in any HTML or JSX template without extra imports—just like you would with native elements such as<div>or<button>.
In short: Stencil handles global registration of all your components (within your app/library's scope) during the build process. This lets you use their tag names directly in any other component's template without importing the component class first, keeping your code clean while retaining full type safety.
内容的提问来源于stack exchange,提问作者Abhishek Gangwar

