Web 组件和 Angular 18

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

Angular 17 到 18 对于 Web 组件(独立元素)有哪些变化? 我已经尝试了一些 Angular 17 相关指南/到目前为止找不到有关 18 更改的任何(有用)信息。

我的设置

main.ts:

import {createApplication} from '@angular/platform-browser';
import {createCustomElement} from "@angular/elements";
import {GridWidgetComponent} from "./app/grid-widget/grid-widget.component";

(async () => {
    const app = await createApplication({
        providers: []
    });

    const gridElement = createCustomElement(GridWidgetComponent, {
        injector: app.injector,
    });

    customElements.define("grid-widget", gridElement);
})();

PHP Storm 在我的 main.ts 中通知我:“表达式语句不是赋值或调用”

index-test.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>

<grid-widget></grid-widget>
<script src="component-lib.js" type="module"></script>

</body>
</html>

脚本链接为 type=module,因为有一条语法错误消息: 未捕获的语法错误:意外的标记“导出”(位于 component-lib.js:3:144),但没有更改任何内容

src/app/grid-widget/grid-widget.component.ts:

import { Component } from '@angular/core';
import {CommonModule} from "@angular/common";

@Component({
  selector: 'grid-widget',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './grid-widget.component.html',
  styleUrl: './grid-widget.component.scss'
})
export class GridWidgetComponent {
  constructor() {
  }
}

角度.json:

...
"architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser-esbuild",
          "options": {
            "outputPath": "dist/webcomponent-example",
            "index": "src/index.html",
            "main": "src/main.ts",
...

package.json:

...
 "build": "ng build --output-hashing=none --configuration production",
 "package" : "npm run build && cat dist/webcomponent-example/{polyfills,main}.js > dist/component-lib.js",
...
"dependencies":{
...
"@angular/elements": "^18.2.1",
...
"@angular/platform-browser": "^18.1.0",
...
}

结果是控制台中出现错误,“Nt”已经被声明: 当使用 type=module 而不使用 type=module 时,“未捕获的语法错误:标识符 'Nt' 已被声明” 我遇到了关于导出的语法错误: “未捕获的语法错误:意外的标记‘导出’”

我使用过的教程之一是 https://www.youtube.com/watch?v=sDf4PFC_Vok&t=508s 在文档中我只找到了https://angular.dev/guide/elements但它没有显示如何正确构建它。

目标是拥有一个可以嵌入到 PHP 站点中的 Web 组件(显然是网格以及后来的其他组件)。因为同一页面上可能有多个实例,所以我认为 WebComponents/Elements 将是一个可行的解决方案。

有人获得了有关如何使用 Angular 18 创建 Web 组件的良好参考吗?

angular web-component angular-elements angular18
1个回答
0
投票

好的,我发现了问题 - 该问题依赖于捆绑器脚本,该脚本应将 polyfills.js 和 main.js 合并到一个“bundle.js”文件中:

...
"package": "npm run build && cat dist/widgets/browser/{polyfills,main}.js > dist/widgets/browser/bundle.js",
...

使用 polyfills.js 和 main.js 时没有问题,一切都很顺利。

© www.soinside.com 2019 - 2024. All rights reserved.