Search code examples
javascripttypescriptstenciljs

Stencil.js: How to use utils function in index.html


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)?


Solution

  • 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>