You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Angular库编译为包含全部依赖的Web Components单文件?

将Angular库编译为独立Web Components单文件的方案

前提条件

确保你的Angular版本在12及以上,Angular Elements的支持更稳定完善。

步骤1:配置库的打包参数

  • 修改库根目录下的ng-package.json,添加单文件打包相关配置:
    {
      "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
      "dest": "../../dist/your-library-name",
      "lib": {
        "entryFile": "src/public-api.ts",
        "format": ["esm2020"],
        "singleBundle": true
      }
    }
    
  • 调整tsconfig.lib.json的compilerOptions,跳过依赖库的类型检查,避免打包报错:
    "compilerOptions": {
      "skipLibCheck": true,
      // 保留原有其他配置
    }
    

步骤2:配置Angular CLI打包选项

在项目根目录的angular.json中,找到你的库对应的build配置,在options里启用单文件打包:

"projects": {
  "your-library-name": {
    "architect": {
      "build": {
        "options": {
          "singleBundle": true,
          // 保留原有其他配置
        }
      }
    }
  }
}

步骤3:确保Web Components正确导出

在库的public-api.ts中,完成自定义元素的注册逻辑:

import { createCustomElement, Injector, NgModule } from '@angular/core';
import { MyCustomComponent } from './components/my-custom.component';

@NgModule({
  declarations: [MyCustomComponent],
  exports: [MyCustomComponent]
})
class MyCustomModule {}

export function defineCustomElements(injector: Injector) {
  const customElement = createCustomElement(MyCustomComponent, { injector });
  customElements.define('my-custom-element', customElement);
}

步骤4:执行打包命令

运行生产环境打包命令,生成独立单文件:

ng build your-library-name --configuration production

验证结果

打包完成后,dist/your-library-name目录下会生成一个独立的JS文件(如your-library-name.js)。在非Angular项目中直接引入该文件,即可使用自定义元素<my-custom-element></my-custom-element>,无需额外引入Angular Core等依赖。

注意事项

  • 尽量避免引入Angular Router等重型非必要依赖,防止单文件体积过大
  • 若使用第三方依赖,确保其支持Tree Shaking,减少冗余代码

内容的提问来源于stack exchange,提问作者Andrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 08:45:46