lit 元素 CDN 汇总包文件:从外部 jsp 文件访问 cdn 包文件中包含的功能

问题描述 投票:0回答:1

我使用 rollup.config.js 创建了一个简单的 lit 元素包文件。此捆绑文件上传到 Netstorage 中。这就是我点亮的元素的样子:

import {customElement} from "lit/decorators.js";
import {LitElement} from "lit";

@customElement('my-lit-element')
export class MyLitElement extends LitElement {

  constructor() {
    super();
    console.log('this is test log');
  }

  /**
   * invoked when a component is added to the document's DOM
   */
  connectedCallback() {
    super.connectedCallback();
  }

    testMethod() {
      console.log('Hi from testMethod()');
    }

}

declare global {
  interface HTMLElementTagNameMap {
    'my-lit-element': MyLitElement;
  }
}

我的 rollup.config.json:

import merge from 'deepmerge';
import { createSpaConfig } from '@open-wc/building-rollup';
import json from "@rollup/plugin-json"

// import copy from 'rollup-plugin-copy'
import pkg from './package.json'
 
const baseConfig = createSpaConfig({
  developmentMode: process.env.ROLLUP_WATCH === 'true',
  injectServiceWorker: false
});
 
export default merge(baseConfig, {
  // any <script type="module"> inside will be bundled by rollup
  input: './index.html',
  plugins: [
    // ... other rollup plugins
    json()
  ]
});

index.html 指向 MyLitElement.js

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Single Page Application</title>
</head>
<body>
    <script type="module" src="./out-tsc/src/MyLitElement.js"></script>
</body>
</html>

我已将捆绑文件嵌入到外部 jsp/html 文件中,并包含用于执行 lit 元素的标签:

bundle 文件有一个公共函数 testMethod(console.log('this is test'))。我想从 jsp.

访问 testMethod()

这是我到目前为止尝试过的

//jsp文件:

 <script type="module" src="https:path_to_my-lit-element-cdn_bundleFile.js"></script>
 <my-lit-element></my-lit-element>
<script>
var dcfVar = document.querySelector("my-lit-element");
console.log("dcfvar", dcfVar) 
dcfVar.testMethod();
</script>

在 dcfVar.testMethod() 失败; ==> 说

Uncaught TypeError: dcfVar.testMethod is not a function

任何人都可以帮助解决这个错误。是否可以从外部访问这些方法?

尝试从外部 jsp 调用 testMethod()

预期 ==> 查看控制台日志:“来自 testMethod 的嗨”

web-component cdn rollupjs lit
1个回答
0
投票

调用测试方法的

<script>
在自定义元素可以注册之前同步运行,因为
<script type="module">
被延迟。

为了确保在组件可用时调用测试方法,您可以利用

whenDefined
.

<script type="module" src="https:path_to_my-lit-element-cdn_bundleFile.js"></script>
<my-lit-element></my-lit-element>
<script>
  customElements.whenDefined('my-lit-element').then(() => {
    const el = document.querySelector('my-lit-element');
    el.testMethod();
  });
</script>
© www.soinside.com 2019 - 2024. All rights reserved.