首页 > 解决方案 > 如何将 Angular Elements 与“ng g library”方法混合使用?

问题描述

如您所知,“ng g library”方法帮助我们创建可重用组件的库。但是,如果我希望通过 Angular Elements 的支持将这些组件编译成 Web 组件呢?不仅如此,lib 中的每个组件都将被编译到自己的文件夹或 JS 文件中。如何配置可以让我实现这一目标的开发环境?

例如:

如果我创建一个Lib并添加一个自定义组件,我知道我可以编译它,生成一系列文件夹,例如esm5,esm2015,fesm5等。现在,问题是:我如何添加,比如说30个自定义组件添加到我的库中,然后当我编译时,它会为每个组件创建一个文件夹,其中包含它们的 Web 组件版本......好像 Angular Elements 遍历了我的组件库并生成了每个组件的 Web 组件版本.

像这样:

lib/
lib/custom/comp1
lib/custom/comp2
lib/custom/comp3
lib/custom/comp4

变成类似的东西:

Dist/
Dist/custom/
Dist/custom/bundle
Dist/custom/esm5
Dist/custom/esm2015
Dist/custom/comp1_web_independend_component_version
Dist/custom/comp2_web_independend_component_version
Dist/custom/comp3_web_independend_component_version
Dist/custom/comp4_web_independend_component_version

我找到的最接近的解决方案是:

https://medium.com/@rahulsahay19/running-multiple-angular-elements-on-the-same-page-5949dac5523

我还请求 Angular CLI 团队提供帮助:

https://github.com/angular/angular-cli/issues/13999

标签: angularangular-cling-packagrangular-elements

解决方案


ng build内部使用 webpack 进行构建。所以这个问题实际上分解为两个部分。

  1. 如果没有ng eject,如何利用内部 webpackConfig 并根据我们的需要对其进行自定义。
  2. 对于这个用例,期望的 webpackConfig 是什么样的。

对于第 1 部分,有一个解决方案@angular-builders/custom-webpack。基本上它允许您将一些额外的字段合并到内部 webpackConfig 中,并且仍然使用官方的“@angular-devkit/build-angular:browser”作为构建器。

现在对于第 2 部分,您的用例只是 webpack 中的多入口多输出构建问题。解决方案非常简单。

const partialWebpackConfig = {
  entry: {
    'custom/comp1': '/path/to/src/lib/custom/comp1.ts',
    'custom/comp2': '/path/to/src/lib/custom/comp2.ts',
  },
  output: {
    path: path.resolve(__dirname, 'Dist'),
    filename: '[name].js'
  }
}

以下是设置此配置的分步说明。

  1. npm install @angular-builders/custom-webpack
  2. webpack.config.js在您的项目根目录中创建一个:
const path = require('path');
module.exports = {
  entry: {
    'custom/comp1': path.resolve(__dirname, 'src/lib/custom/comp1.ts'),
    'custom/comp2': path.resolve(__dirname, 'src/lib/custom/comp2.ts')
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
  }
}
  1. 编辑“architect.build”字段angular.json
{
  // ...
  "architect": {
    "build": {
      "builder": "@angular-builders/custom-webpack:browser",
      "options": {
        "customWebpackConfig": {
          "path": "./webpack.config.js",
        },
        // ...
  1. 运行ng build,应该会看到结果。

对于高级使用,值得一提的是,@angular-builders/custom-webpack支持将webpack 配置导出为函数,以完全控制最终使用的 webpackConfig。


推荐阅读