gpt4 book ai didi

Angular CLI 依赖项——如果我不使用它,为什么需要安装 @angular/router?

转载 作者:太空狗 更新时间:2023-10-29 18:20:18 28 4
gpt4 key购买 nike

当我启动一个空白的 Angular CLI 项目时,package.json 中的这些依赖项看起来不是必需的,因此我尝试删除它们(以及从导入中删除 FormModules 和 HttpModules):

@angular/forms": "^4.0.0",
@angular/http": "^4.0.0",
@angular/router": "^4.0.0",

但是当我尝试构建项目时,出现错误:

'无法解析模块@angular/router'中的错误

在我看来更奇怪的是,在重新保存文件后,项目成功重建并且运行正常。

有人可以解释一下@angular/router 的这种隐藏依赖关系在哪里吗?

我的文件:

应用程序模块.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

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

应用程序组件.ts:

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
template: '<h1>test</h1>'
})
export class AppComponent {}

最佳答案

Angular cli 使用 @ngtool/webpack 插件,该插件使用来自 @angular/compiler-cli 的私有(private) API 来获取延迟加载的路由

plugin.ts

const {__NGTOOLS_PRIVATE_API_2} = require('@angular/compiler-cli');

https://github.com/angular/angular-cli/blob/v1.0.1/packages/%40ngtools/webpack/src/plugin.ts#L7

// We need to run the `listLazyRoutes` the first time because it also navigates libraries
// and other things that we might miss using the findLazyRoutesInAst.
let discoveredLazyRoutes: LazyRouteMap = this.firstRun ?
__NGTOOLS_PRIVATE_API_2.listLazyRoutes({
program: this._program,
host: this._compilerHost,
angularCompilerOptions: this._angularCompilerOptions,
entryModule: this._entryModule
})
: this._findLazyRoutesInAst();

https://github.com/angular/angular-cli/blob/v1.0.1/packages/%40ngtools/webpack/src/plugin.ts#L492-L501

注意 this.firstRun。这就是您在第一次运行时遇到错误的原因。

@angular/compiler-cli/src/ngtools_impl.ts

const ROUTER_MODULE_PATH = '@angular/router';

https://github.com/angular/angular/blob/4.1.0/packages/compiler-cli/src/ngtools_impl.ts#L20

这里是复制

enter image description here

另见

关于Angular CLI 依赖项——如果我不使用它,为什么需要安装 @angular/router?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43717367/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com