Website-Suche

javascript - Stencil.js: Wie man die Utils-Funktion in index.html verwendet


Ich erstelle eine Popup-Komponente in StencilJS.

Dateistruktur:

  • Popup-Element

    • src

      • Dienstprogramme

        • Popup-Manager
        • utils
        • popup-manager

        • src
        • utils
        • popup-manager

      • Komponenten

        • Popup-Element

          • popup-element.tsx
          • Popup-Element
          • popup-element.tsx

      • index.html
    • ...

Jetzt versuche ich, eine Komponente aus einer Funktion in das DOM einzufügen: 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);
}

Wie kann ich diese Funktion in index.html (im Entwicklungsmodus) verwenden?

Antwort #1

Update:

Sie können Exporte zu src/index.ts hinzufügen, und diese werden dann unter /build/index.esm.js verfügbar sein.

// src/index.ts

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

  createMiniNotification('Hi');
</script>

Ursprüngliche Antwort:

Ich würde vorschlagen, dass Sie eine Wrapper-Komponente erstellen, z. B. app-root, und Ihre Funktion von dort aus aufrufen, z. B. in ihrem componentDidLoad-Lebenszyklus-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 />;
  }
}

Dann können Sie einfach diese Wrapper-Komponente in Ihre index.html hinzufügen:

<app-root></app-root>

Verwandte Artikel