ionic-team / stencil-component-starter

Minimal starter project for building shareable web components with Stencil
https://github.com/ionic-team/stencil
MIT License
278 stars 129 forks source link

What's the correct way to import a Stencil component? #112

Open dave-kennedy opened 2 years ago

dave-kennedy commented 2 years ago

I followed the instructions to build my project with npm run build and then published the dist and loader folders with npm publish. Now, I want to add the component to a regular HTML page. The readme instructs to add this to the page head to import the component from unpkg:

<script type="module" src="https://unpkg.com/wow-mum-component@1.0.1/dist/wow-mum-component.esm.js"></script>

That file doesn't exist. Instead, this seems to work:

<script type="module" src="https://unpkg.com/wow-mum-component@1.0.1/dist/wow-mum-component/wow-mum-component.esm.js"></script>

This also seems to work:

<script type="module" src="https://unpkg.com/wow-mum-component@1.0.1"></script>

Which of these latter two is "correct"? Or are they the same?

Also, src/index.html has two script tags - one for modern browsers that support ES modules and one for older browsers that don't:

<script type="module" src="/build/wow-mum-component.esm.js"></script>
<script nomodule src="/build/wow-mum-component.js"></script>

But the readme doesn't say what the second tag should look like for unpkg. I tried a few guesses but none of these appear to do anything:

<script nomodule src="https://unpkg.com/wow-mum-component@1.0.1"></script>
<script nomodule src="https://unpkg.com/wow-mum-component@1.0.1/index.js"></script>
<script nomodule src="https://unpkg.com/wow-mum-component@1.0.1/index.cjs.js"></script>

I'm also confused about how to import/require the component in a Node module/script. Here's my try at importing it in a module:

import { WowMumComponent } from 'wow-mum-component';
console.log(WowMumComponent);

The above throws this error:

file:index.mjs:2
import { WowMumComponent } from 'wow-mum-component';
         ^^^^^^^^^^^^^^^
SyntaxError: Named export 'WowMumComponent' not found. The requested module 'wow-mum-component' is a CommonJS module, which may not support all module.exports as named exports.

And here's my try at requiring it in a script:

const { WowMumComponent } = require('wow-mum-component');
console.log(WowMumComponent);

The above doesn't throw an error but just logs undefined.

To summarize, I have four questions, all related to importing and using a published component:

  1. How do I import the component as an ES module on an HTML page?
  2. How do I import the component for older browsers on an HTML page (the nomodule fallback)?
  3. How do I import the component as an ES module in a Node module?
  4. How do I require the component as a CommonJS module in a Node script?