ng 17 中存在从 Angular 工作区外部导入的独立组件的问题

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

顺序

git clone https://github.com/thomaspeugeot/multi_ws_issue.git
cd multi_ws_issue
cd a
npm i
ng build

意想不到的结果

$ ng build
Application bundle generation failed. [6.929 seconds]

X [ERROR] Could not resolve "@angular/core"

    ../b/src/app/b/b.component.ts:1:26:
      1 │ import { Component } from '@angular/core';
        ╵                           ~~~~~~~~~~~~~~~
...

分析

描述

此存储库包含两个目录,“a”和“b”。每个都是一个有角度的工作空间。 “a”工作区的应用程序根组件直接从“b”工作区导入独立的“BComponent”。

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';

import { BComponent } from '../../../b/src/app/b/b.component'


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BComponent,
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

按照上述顺序,

ng build
无法正确解析“BComponent”中的依赖关系。

需要在“b”工作区中安装依赖项来构建“AComponent”。

cd ../b
npm i
cd ../a
ng build

...
Application bundle generation complete. [8.837 seconds]

应用程序正确显示。

问题:在依赖工作区中安装模块并不是最佳选择。

为什么直接跨工作区导入而不是通过库导入很重要?

在提出这个问题之前,请先阅读以下内容。

导入是直接导入工作区之外的组件。这与 Angular 正确的方式相反,即通过库导入组件(请参阅https://angular.dev/tools/libraries/creating-libraries)。

正确的方法是在“b”工作区中构建“BLib”库,将独立的 BComponent 包含到“Blib”中,将“BLib”库作为模块发布到私有存储库中,然后将其导入到“通过在 node_modules 中正确导入来创建“工作区。

不幸的是,这种“正确的方式”并不适合这里。如果在“b”工作区中构建“B”组件,则意味着将额外的 400 MB 模块添加到“b”工作区 node_modules 中。这是一个示例存储库,但在实际应用程序存储库中,一个工作区通常会从 5 个或更多其他工作区导入组件 (https://github.com/fullstack-lang/gonggantt)。这可以转化为 GB 的 node_modules 内容。对于 Angular v16,在工作区外部导入确实有效,但对于 Angular v17,这个技巧不再起作用。有数十个这样的存储库,中端计算机根本没有足够的磁盘空间。

此外,独立组件的想法似乎是减少对模块的需求(参见 Angular 网站)。

独立组件提供了构建 Angular 应用程序的简化方法。独立组件、指令和管道旨在通过减少对 NgModules 的需求来简化创作体验

问题

“a”工作区配置是否有启用直接导入的技巧?

注意:保留 esbuild 是一个理想的结果,否则技术债务将会增加。

暂定解决方案

在“a”工作区的tsconfig.json中,告诉编译器使用本地node_modules。

    "paths": {
      "*": [
        "./node_modules/*"
      ]
    }

编译没问题,但运行时出现错误

ERROR Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`. Find more at https://angular.io/errors/NG0203
    Angular 46
    <anonymous> main.ts:5
core.mjs:6531:22
...

对此错误的任何解释/解决此需求的任何想法都将受到欢迎。

angular angular17 angular-standalone-components
1个回答
0
投票

找到解决方案,使用 npm 工作区

恰好问题可以通过使用 npm 工作空间来解决。

https://docs.npmjs.com/cli/v9/using-npm/workspaces?v=true

npm 工作空间允许为多个工作空间使用相同的 node_modules 目录

git clone https://github.com/thomaspeugeot/multi_ws_issue.git
cd multi_ws_issue
git checkout  npm-workspace
npm i
cd a
ng serve
© www.soinside.com 2019 - 2024. All rights reserved.