简体   繁体   中英

StencilJS using component in HTML file

I want to use a component created using StencilJS in a regular basic HTML file. I followed these steps:

I have created a stencil component to create the basic my-component example:

npm init stencil

I want to use this component in an HTML file, so I ran

npm run build

I then created an html project with the following structure:

在此处输入图像描述

And then I moved the files from the dist folder into the script folder. And I added script tag in the head of my html file that references the component.js file like this:

<script src="script/{component_name}/{component_name}.js"></script>

And I used the component in the html like this:

<my-component first="Stencil" last="'Don't call me a framework' JS"></my-component>

But my component isn't being rendered. I get an error involving a esm.js file. Can someone help me with this process of compiling my stencil component to be using in a basic HTML project?

Stencil bundles your dist into modules and lazy-loads only the required code based on the components you are actually using in your HTML. So you should serve the whole dist folder along with your website.

The recommended way is to have the following two script tags in your html file:

<script type="module" src="/dist/[namespace]/[namespace].esm.js"></script>
<script nomodule src="/dist/[namespace]/[namespace].js"></script>

(where [namespace] is whatever is set in your stencil.config.ts )

This will instruct browsers who support ES Modules to use the esm bundle, and other browsers will use the ES5 (cjs) bundle.

If my-component is the only component that you're using from your library, then only that code will be lazy-loaded by your page. Stencil knows about component interdependencies and how to lazy-load them accordingly.


There is a new experimental output target (called custom-elements-bundle ) that allows you to bundle everything into one js file, which will simplify distribution in some cases. It's only available with the new refactored compiler (which is available using the --next flag, after installing @stencil/core@next ) (Stencil 2 has been out for a while now).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM