无法呈现 Web 组件
Can not render web component
我无法呈现我的 Web 组件。我创建了一个 class HelloWC.ts
,它只有一个任务(在 <h2>
标签内渲染 Hello)。我使用 tsconfig.json
来定义如何构建 /dist 目录,其中包含 HelloWC
class 翻译成 es6 。在 index.html
文件中,我添加了 <script>
标签(在 <body>
的末尾),我在其中从 /dist[=51 导入了我的 HelloWC
组件=] 目录。然后我想在 index.html
<body>
标签内渲染我的 <hello-wc>
组件。如果我检查由 server-http
提供的 index.html
,我可以看到有一个 <hello-wc></hello-wc>
标签,但它是空的。在网卡中我也可以看到 HelloWC.js 下载成功。我还在我的组件的构造函数中添加了一个简单的 console.log()
但消息从未被记录(看起来我的组件从未被创建)。我不知道为什么我的组件无法正确呈现。如果您有任何想法,请告诉我。
HelloWC.ts
const template: string = `<div>
<h2>Hello</h2>
</div>`;
export class HelloWC extends HTMLElement {
shadowRoot!: ShadowRoot;
public static TAG = 'hello-wc';
constructor() {
super();
console.log('heelo wc');
this.attachShadow({ mode: 'open'});
this.shadowRoot.innerHTML = template;
}
}
customElements.define(HelloWC.TAG, HelloWC);
index.html
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<title>Hello WC</title>
</head>
<body>
<hello-wc></hello-wc>
<script src="/dist/HelloWC.js" type="module"></script>
</body>
</html>
tsconfig.json
{
"compilerOptions": {
"module": "umd",
"target": "es6",
"sourceMap": true,
"noImplicitAny": true,
"strictNullChecks": true,
"removeComments": true,
"moduleResolution": "node"
},
"exclude": [
"src",
"node_modules",
"dist"
]
}
项目结构
看来您是将编译后的文件导入为ES模块,但是,tsconfig.json
您指定了"module": "umd"
(应该是es6
或esnext
而不是umd
如果你想要 ES 模块)
我无法呈现我的 Web 组件。我创建了一个 class HelloWC.ts
,它只有一个任务(在 <h2>
标签内渲染 Hello)。我使用 tsconfig.json
来定义如何构建 /dist 目录,其中包含 HelloWC
class 翻译成 es6 。在 index.html
文件中,我添加了 <script>
标签(在 <body>
的末尾),我在其中从 /dist[=51 导入了我的 HelloWC
组件=] 目录。然后我想在 index.html
<body>
标签内渲染我的 <hello-wc>
组件。如果我检查由 server-http
提供的 index.html
,我可以看到有一个 <hello-wc></hello-wc>
标签,但它是空的。在网卡中我也可以看到 HelloWC.js 下载成功。我还在我的组件的构造函数中添加了一个简单的 console.log()
但消息从未被记录(看起来我的组件从未被创建)。我不知道为什么我的组件无法正确呈现。如果您有任何想法,请告诉我。
HelloWC.ts
const template: string = `<div>
<h2>Hello</h2>
</div>`;
export class HelloWC extends HTMLElement {
shadowRoot!: ShadowRoot;
public static TAG = 'hello-wc';
constructor() {
super();
console.log('heelo wc');
this.attachShadow({ mode: 'open'});
this.shadowRoot.innerHTML = template;
}
}
customElements.define(HelloWC.TAG, HelloWC);
index.html
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<title>Hello WC</title>
</head>
<body>
<hello-wc></hello-wc>
<script src="/dist/HelloWC.js" type="module"></script>
</body>
</html>
tsconfig.json
{
"compilerOptions": {
"module": "umd",
"target": "es6",
"sourceMap": true,
"noImplicitAny": true,
"strictNullChecks": true,
"removeComments": true,
"moduleResolution": "node"
},
"exclude": [
"src",
"node_modules",
"dist"
]
}
项目结构
看来您是将编译后的文件导入为ES模块,但是,tsconfig.json
您指定了"module": "umd"
(应该是es6
或esnext
而不是umd
如果你想要 ES 模块)