簡體   English   中英

Stencil.js:如何在 index.html 中使用 utils 函數

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

我正在創建一個彈出 stenciljs 組件。

文件結構:

  • 彈出元素
    • 源文件
      • 實用程序
        • 彈出式管理器
      • 成分
        • 彈出元素
          • popup-element.tsx
      • 索引.html
    • ...

現在我嘗試從函數插入組件到 DOM: 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);
}

如何在 index.html 中使用這個函數(在開發模式下)?

更新:

您可以將導出添加到src/index.ts ,然后這些將在/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>

原答案:

我建議您創建一個包裝組件,例如app-root並從那里調用您的函數,例如在其componentDidLoad生命周期鈎子中:

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 />;
  }
}

然后你可以在你的index.html添加這個包裝器組件:

<app-root></app-root>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM