angular - 如何将 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 团队提供帮助:
解决方案
ng build
内部使用 webpack 进行构建。所以这个问题实际上分解为两个部分。
- 如果没有
ng eject
,如何利用内部 webpackConfig 并根据我们的需要对其进行自定义。 - 对于这个用例,期望的 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'
}
}
以下是设置此配置的分步说明。
npm install @angular-builders/custom-webpack
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'
}
}
- 编辑“architect.build”字段
angular.json
:
{
// ...
"architect": {
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./webpack.config.js",
},
// ...
- 运行
ng build
,应该会看到结果。
对于高级使用,值得一提的是,@angular-builders/custom-webpack
支持将webpack 配置导出为函数,以完全控制最终使用的 webpackConfig。
推荐阅读
- javascript - 如何从具有公共字段的三个数组中创建一个数组
- ssas - 具有硬编码成员的 SSAS 命名集
- dataframe - 在 Stata 中为多个成员资格多级模型准备数据
- flutter - 如何在颤振中创建六位唯一代码
- google-sheets - 表格公式帮助:如果列标题匹配,则将所有匹配值组合在一起(A、B、C,而不是 A+B+C)
- solr - 在 solr 中保留多值的关联或位置
- node.js - NVM(适用于 Windows)看不到本地可执行脚本
- javascript - 如何从复选框和 div 类获取日期到数组
- google-cloud-platform - 数据流模板 - Splunk 不从主题读取数据
- vhdl - VHDL 中的 5 位约翰逊计数器模拟仅打印零