【问题标题】:Path aliases for Angular library project not wokringAngular 库项目的路径别名不起作用
【发布时间】:2021-02-10 09:42:44
【问题描述】:

我正在尝试使用 ui 元素实现 Angular 库。该库是一个monorepo,然后像这样发布

@lib/core
@lib/i18n
@lib/ui

正在 Storybook 下进行开发。

这是我的结构。

projects
    lib
        core
        i18n
        ui
tsconfig.json

ui目录下的组件依赖于core和i18n目录。

父 tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "module": "esnext",
    "lib": [
      "es2018",
      "dom"
    ],
      "paths": {
        "@lib/core": ["projects/lib/core/src/*"],
        "@lib/i18n": ["projects/lib/i18n"]
    }
  },
  "angularCompilerOptions": {
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}
  • i18n 目录不包含 src 文件夹。

i18n 目录中的文件已正确解析,我可以 ctrl+单击它们(使用 phpstorm)移动到文件。

来自@lib/core 的文件在编译期间抛出这些错误

ERROR in /path/to/project/projects/lib/ui/src/lib/widgets/help/components/widget-button/cl-widget-button.component.ts
TS2307: Cannot find module '@lib/core' or its corresponding type declarations.

也是核心目录的结构

public-api.ts 是我的入口点,包括所有导出

// index.ts
export * from './public-api.ts';

我使用类型别名的原因是为了模拟生产,比如导入,所有的包都将通过 npm 单独安装。

如果我使用相对路径 (../../../../path/to/core),那么一切都会按其应有的方式构建和运行,但在生产中,这条路径当然不存在。

我尝试了什么:

  • rootDirs 打字稿选项没有任何运气。
  • "@lib/core/*": ["projects/lib/core/src/*"],在没有任何运气的路径中。
  • 将路径选项放在不同的 tsconfig 文件中,例如在 ui/tsconfig.json 中,没有任何运气。事实上,在这种情况下,i18n 也停止了工作。

我开始相信我不能为这样的结构做别名。

我在这里错过了什么?

【问题讨论】:

  • 嗨!你找到解决这个问题的方法了吗?如果是的话,你能在这里分享一下吗?我刚碰到一个类似的。
  • 我设法找到了解决方案,是的,我会在接下来的几天里尝试在这里解释它。谢谢。

标签: angular typescript tsconfig


【解决方案1】:

我可以提供我的解决方案

  1. 在根tsconfig.json 中输入:
    "paths": {
      "@lib/core": [
        "dist/lib/core", // it depends on your library name
        "dist/core"
      ],
      ...
    }
  1. 像这样在package.json中添加命令
"start:storybook": "ng build lib && ng serve storybook"

【讨论】:

    猜你喜欢
    • 2019-03-03
    • 2022-08-03
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2022-06-20
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多