Angular9中的短TypeScript导入路径

When working with Angular, importing files in TypeScript is something we do quite often. When we import files from other parent directories, the IDE typically resolves the import file paths. Furthermore, when we build the Angular application, the TypeScript compiler compiles the code and produces the final JavaScript bundle with the help of Webpack. Since these essential steps are taken care of, most of us won’t bother in improving these import paths.

在使用Angular时,我们经常在TypeScript中导入文件。 当我们从其他父目录导入文件时,IDE通常会解析导入文件路径。 此外,当我们构建Angular应用程序时,TypeScript编译器将编译代码并在Webpack的帮助下生成最终JavaScript包。 由于这些基本步骤已得到处理,因此我们大多数人都不会为改善这些导入路径而烦恼。

However, there are several downsides of not standardizing these paths in the long run. In this article, I will first explain why you should do it as the first thing in any Angular project and then guide you through the steps of doing it.

但是,从长远来看,不标准化这些路径存在一些弊端。 在本文中,我将首先解释为什么在任何Angular项目中都应首先进行操作,然后指导您完成操作。

为什么标准化TypeScript导入路径很重要? (Why it’s important to standardize TypeScript import paths?)

There are several reasons why you should set up import path aliases for your Angular project.

有几个原因为您的Angular项目设置导入路径别名。

看起来不错 (Looks Nice)

The first thing you will notice once you add the path aliases is the clarity of import paths where we can quickly figure out the location of the file. You can compare the following two examples to understand this. First, let’s look at how a component code looks like without import aliases.

添加路径别名后,您会注意到的第一件事是导入路径的清晰度,在这里我们可以快速确定文件的位置。 您可以比较以下两个示例以了解这一点。 首先,让我们看一下没有导入别名的组件代码的外观。

import { Component, OnInit } from '@angular/core';import { ArticleForm } from '../../../views/article-form/article-form';

This code will change to the following once we add the path alias for views.

添加视图的路径别名后,此代码将更改为以下代码。

import { Component, OnInit } from '@angular/core';import { ArticleForm } from '@views/article-form/article-form';

Just think of having several imports with relative paths, some with deep references, how ugly it can be. I feel that the latter looks way much better for the clarity of the imports.

只需考虑具有相对路径的多个导入,其中一些具有较深的引用,就可以做到多么丑陋。 我认为后者对于进口的清晰度看起来要好得多。

定义编码风格 (Defines a Coding Style)

Another important aspect of having path aliases is that the aliases itself will act as a document of not mixing relative and absolute paths. Otherwise, if the developer chooses the absolute or relative paths based on the preference, it wouldn’t be uniform. Therefore, by defining the set of aliases, we can update the coding styles to follow the aliases conversions defined for the project.

具有路径别名的另一个重要方面是,别名本身将充当不混合相对路径和绝对路径的文档。 否则,如果开发人员根据偏好选择绝对路径或相对路径,则路径将不一致。 因此,通过定义别名集,我们可以更新编码样式以遵循为项目定义的别名转换。

帮助重构 (Helps Refactoring)

More than the above two reasons, the support for refactoring comes as the most important advantage when using aliases. When we move the folder or a file within the Angular project, the IDE does a great job of correcting some of the imports. But it was tough to modify the remaining relative paths since we have to change it for another relative place. After having the proper aliases, it became way much easier to deal with manual path changes.

除上述两个原因外,使用别名时,对重构的支持是最重要的优势。 当我们在Angular项目中移动文件夹或文件时,IDE在纠正某些导入方面做得很好。 但是很难修改其余的相对路径,因为我们必须将其更改为另一个相对位置。 使用适当的别名后,它变得更容易处理手动路径更改。

Besides, if you want to make the automatic imports from VSCode to use absolute paths, you can follow the below two steps.

此外,如果要从VSCode自动导入以使用绝对路径,则可以执行以下两个步骤。

  • Step 1: In VSCode, go toFile>Preferences>Settings>User Settings

    步骤1:在VSCode中,转到“ File>Preferences>Settings>User Settings

  • Step 2: Search property typescript.preferences.importModuleSpecifier and sets its value non-relative.

    步骤2:搜索属性typescript.preferences.importModuleSpecifier并将其值设置为non-relative

Tip: Use Bit (Github) to share, document, and manage reusable Angular components from different projects. It’s a great way to increase code reuse, speed up development, and build apps that scale.

提示 :使用Bit ( Github )可以共享,记录和管理来自不同项目的可重用Angular组件。 这是增加代码重用,加速开发并构建可扩展应用程序的好方法。

Install shared components with NPM or “clone” and modify with Bit.

使用NPM或“克隆”安装共享组件,并使用Bit进行修改。

Image for post
Bit.dev Bit.dev上共享的角度组件

使用Angular9设置路径别名 (Setting up Path Aliases with Angular9)

When assigning alias short paths, we need to ensure two things. The first thing is that your IDE can highlight whether the import paths are right or wrong. If your IDE cannot recognize the correctness, it is counterproductive. Then the second thing is quite apparent, where the TypeScript compiler needs to identify these paths. So let us look at each step in detail.

分配别名短路径时,我们需要确保两件事。 第一件事是您的IDE可以突出显示导入路径是对还是错。 如果您的IDE无法识别正确性,则适得其反。 然后第二件事很明显,TypeScript编译器需要识别这些路径。 因此,让我们详细了解每个步骤。

步骤1:确定所需的别名 (Step 1: Identify the Aliases you need)

The first step is to identify the list of root directories for these aliases. Remember, having more path aliases doesn’t mean that it will be better since developers have to memorize those. So keeping a few unique ones should be sufficient. I typically think of the dependency structure and set up aliases for the following.

第一步是识别这些别名的根目录列表。 请记住,拥有更多的路径别名并不意味着它将更好,因为开发人员必须记住这些别名。 因此,保留一些唯一的就足够了。 我通常会考虑依赖项结构,并为以下内容设置别名。

  • @app

    @app

  • @views

    @views

  • @containers

    @containers

  • @store

    @store

  • @services

    @services

步骤2:修改tsconfig.json (Step 2: Modify tsconfig.json)

{"compileOnSave": false,"compilerOptions": {  "baseUrl": "./src",  "paths": {    "@angular/*": [ "../node_modules/@angular/*" ],    "@app/*": ["app/*"],    "@views/*": ["app/views/*"],    "@containers/*": ["app/containers/*"],    "@store/*": ["app/store/*"],    "@services/*": ["app/services/*"]},
...}

Note that, here setting up baseUrl is essential to avoid the IDE (I used VSCode) from recognizing the paths correctly for IntelliSense.

需要注意的是,在这里设立baseUrl是必不可少的,以避免无法正确识别的智能感知路径的IDE(我用VSCode)。

步骤3:修改tsconfig.app.json (Step 3: Modify tsconfig.app.json)

After completing Step 2, I found that the Angular9 build isn’t working correctly. Then I realized the issue is there with the tsconfig.app.json file.

完成第2步后,我发现Angular9构建无法正常工作。 然后我意识到tsconfig.app.json文件存在问题。

The difference is I removed the following, path segment in tsconfig.app.json and moved the angular one to tsconfig.json

区别在于我在tsconfig.app.json删除了以下路径段, tsconfig.app.json角度1移动到了tsconfig.json

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

After removing, the tsconfig.app.json doesn't have any reference to paths override, where the Angular9 build uses the paths property defined in tsconfig.json file.

删除后, tsconfig.app.json没有任何对路径覆盖的引用,Angular9构建使用tsconfig.json文件中定义的paths属性。

After following these steps, I had to update the imports across the entire project manually. Therefore, I feel its the best practice you should do at the very early stage of the project to avoid the extra effort.

完成这些步骤后,我必须手动更新整个项目中的导入。 因此,我觉得这是您在项目的早期阶段应避免的最佳实践,以避免额外的工作。

I hope the article is useful to understand the rationally behind using path aliases and the steps to configure it. If you have any questions, feel free to comment below.

我希望本文对理解使用路径别名的合理原理及其配置步骤很有帮助。 如有任何疑问,请在下面发表评论。

学到更多 (Learn More)

翻译自: https://blog.bitsrc.io/short-typescript-import-paths-in-angular9-22ce34bd424d

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值