【问题标题】:TypeScript custom paths do not work without barrelingTypeScript 自定义路径在没有桶的情况下不起作用
【发布时间】:2020-04-20 14:42:15
【问题描述】:

我整个上午都在ts-paths 上度过,以缩短我的导入路径。

我可以确认,如果您设置了桶(一个索引文件导出您的模块),自定义路径可以工作

root
├── client
│   ├──tsconfig.json
│   ├── src
│       ├──app
│           ├── shared
│               ├── services
│                   ├── some.service.ts
├── common
│   ├── index.ts // exports * from each file

我的 NG8 tsconfig.ts 文件:

"compilerOptions": {
    "baseUrl": ".",
    "paths": {
        "@common": ["../common"], // works with barreling
        "@services": ["./src/app/shared/services"] // only works with barreling
    },

@services 不起作用...除非我设置了桶装
(在shared文件夹中添加index.ts文件export * from './some.service';

@common 可以开箱即用,因为像上面这样的桶。

我是否遗漏了什么,或者我所阅读的所有内容都没有要求以这种方式导出模块?

我的研究:
https://angularfirebase.com/lessons/shorten-typescript-imports-in-an-angular-project/
https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping
How to use paths in tsconfig.json?
还有很多...

【问题讨论】:

  • 这应该可以,尝试不带前导./ 只是"src/app/shared/services"。虽然我认为根目录中应该有一个tsconfig.json
  • 嘿@C_Ogoo,所以路径都是正确的,因为它在存在导出服务类的 index.ts 文件时工作......而且我整天都在尝试我能想到的每个路径变化。制作路径 src/app/shared/services 会破坏它...除非具有导出的索引存在,在这种情况下它仍然有效。
  • 啊,我误读/误解了..在服务目录中。你没有桶文件,但是像.../services/some-file.ts这样的个人文件
  • 是的,为了清晰起见,我已经更新了结构。该文件夹中有很多服务文件。

标签: angular typescript path angular-module


【解决方案1】:

根据您的设置(没有桶index.ts 文件),您的路径需要稍有不同。

"paths": {
  "@services/*": ["src/app/shared/services/*"],
},

然后您就可以使用以下方式导入:

import { SomeService } from '@services/some.service'

【讨论】:

  • 这行得通!我可以发誓这正是我今天早上开始的方式。但是,它现在有效。感谢您的时间和澄清。
  • 很高兴,很高兴我能帮上忙 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-19
  • 1970-01-01
  • 2018-08-16
  • 1970-01-01
  • 1970-01-01
  • 2014-11-21
相关资源
最近更新 更多