Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 303
Nikolay Stepin Avatar asked Jun 03 '26 12:06

Nikolay Stepin


1 Answers

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>
like image 101
Simon Hänisch Avatar answered Jun 05 '26 00:06

Simon Hänisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!