Skip to content

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

@dave-kennedy

Description

@dave-kennedy

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/[email protected]/dist/wow-mum-component.esm.js"></script>

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

<script type="module" src="https://unpkg.com/[email protected]/dist/wow-mum-component/wow-mum-component.esm.js"></script>

This also seems to work:

<script type="module" src="https://unpkg.com/[email protected]"></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/[email protected]"></script>
<script nomodule src="https://unpkg.com/[email protected]/index.js"></script>
<script nomodule src="https://unpkg.com/[email protected]/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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions