简体   繁体   中英

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

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, eg app-root and call your function from there, eg 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM