【问题标题】:Why my path for import @angular/core is different to online tutorial?为什么我的导入@angular/core 的路径与在线教程不同?
【发布时间】:2018-12-26 17:44:39
【问题描述】:

假设我有以下组件:

@Component({})
export class ServerComponent {

}

输入@Component 时,Visual Studio Code 建议我自动导入@angular/core 模块。我接受并得到了这个导入:

import { Component } from "../../../node_modules/@angular/core";

当我观看在线课程时,我看到导师执行相同的操作时,他的路径要短得多:

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

我的应用在两条路径上都可以正常工作,但我想知道这是怎么发生的,只是出于好奇。

问题:

  • 为什么我的导入路径不同?
  • 是否有任何配置可以控制此行为?
  • 这会影响我的应用的任何行为吗?

我的环境:

  • Windows 10 专业版 x64
  • Visual Studio 代码 1.25.1
  • NPM 5.6.0
  • 节点 8.11.3
  • Angular CLI:6.0.8 (npm install -g @angular/cli)
  • Angular 6.0.9

导师的环境:

  • Mac OSX
  • Visual Studio 代码
  • Angular CLI 6.0.0 (npm install -g @angular/cli)

【问题讨论】:

标签: node.js angular npm visual-studio-code


【解决方案1】:

答案

  1. 这只是 Visual Studio 工作方式的绝对路径差异,它会将项目文件夹下的 node_modules 添加到您的工作区,因此它会建议您使用 node_modules 的绝对路径,在您的情况下为 @angular/core。在您看到的教程中,或者通常我们只提供@angular/core 导入,因为在运行时角度编译器会将路径解析为绝对路径,即..,'../../../node_modules/@angular/core'。
  2. 没有配置控制来明确定义它,而是 Angular 编译器行为或 Angular 生态系统的构建方式,因为编译后所有模块都会被调用并注入到主组件中。
  3. 不,它不会影响您应用的任何行为。

【讨论】:

    【解决方案2】:

    看看你的主路径中的tsconfig.json

    为导入定义了(或可以是)快捷方式。 好像

    "paths": {
          "@modules/*": ["app/modules/*"],
          "@core/*": ["app/core/*"],
          "@shared/*": ["app/shared/*"]
        }
    

    这样app/modules/MyModule/SomeComponent 中的所有内容都可以导入为@modules/MyModule/SomeComponent

    热烈的问候

    【讨论】:

      猜你喜欢
      • 2017-07-18
      • 1970-01-01
      • 2018-02-17
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 2013-05-26
      相关资源
      最近更新 更多