3

i'm creating a popup stenciljs component.

File structure:

  • popup-element
    • src
      • utils
        • popup-manager
      • components
        • popup-element
          • popup-element.tsx
      • index.html
    • ...

Now i try to insert component to DOM from function: popup-manager.ts

export function createMiniNotification(notificationContent: string, mountTarget: HTMLElement = document.body): HTMLElement {
  const notify = document.createElement('popup-element');
  notify.setAttribute('content', notificationContent);
  mountTarget.appendChild(notify);
}

How can I use this function in index.html (in development mode)?

1 Answers1

4

Update:

You can add exports to src/index.ts and then those will be available at /build/index.esm.js.

// src/index.ts

export const createMiniNotification = (msg: string) => console.log(msg);
<script type="module">
  import { createMiniNotification } from '/build/index.esm.js';

  createMiniNotification('Hi');
</script>

Original Answer:

I'd suggest you create a wrapping component, e. g. app-root and call your function from there, e. g. in its componentDidLoad lifecycle hook:

import { Component, Host, h } from '@stencil/core';
import { createMiniNotification } from '../utils/popup-manager';

@Component({ tag: 'app-root' })
export class AppRoot {
  componentDidLoad() {
    createMiniNotification(/* ... */);
  }

  render() {
    return <Host />;
  }
}

Then you can just add this wrapper component in your index.html:

<app-root></app-root>
Simon Hänisch
  • 4,740
  • 2
  • 30
  • 42