繁体   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