Angular CLI 8."ng serve" 在 tsconfig.json 中使用 "paths" 时失败

Angular CLI 8."ng serve" fails when using "paths" in tsconfig.json

我正在开发一个包含多个基于 Angular 8 的前端的项目。每个前端都是一个单独的 Angular 8 项目,具有自己的文件夹子结构。它们的根文件夹都位于同一个主文件夹中。

theproject
    |___ frontend1
    |___ frontend2
    ...

为了避免重复代码和优化代码重构,我们决定将重复代码放入 "base" 文件夹中,并通过 tsconfig.json 中设置的路径选项导入它。

theproject
    |___ frontend1/
    |___ frontend2/
    ...
    |___ base-ui/

我们从一个简单的 class 开始,表示在整个前端环境中使用的常量集合。此 class 位于文件 constants.ts 内,可在文件夹 base-ui/constants

中找到
theproject
    |___ frontend1/
    |___ frontend2/
    ...
    |___ base-ui/constants/constants.ts

这是我们的tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ],
    "types": [
      "hammerjs",
      "jasmine"
    ],
    "paths": {
      "@shared/*": [
        "../base-ui/*"
      ]
    }
  }
}

这是constants.ts

的非常简单的内容
export class BaseServerConstants {
    public static readonly LOGOUT_URL = 'server/logout';
    public static readonly LOGIN_URL = 'server/login';
}

我们是这样import/use的

import { BaseServerConstants } from '@shared/constants/constants';

...

performLogout(): void {
    window.location.href = BaseServerConstants.LOGOUT_URL;
}

只要我们用 ng buildng build --prod.

编码或构建项目,这就像一个魅力

但是在 IntelliJ 或 VS Code 的控制台中使用 ng serve 总是会导致相同的错误消息:

ERROR in /Users/developer/theproject/base-ui/constants/constants.ts
Module not found: Error: Can't resolve 'tslib' in '/Users/developer/theproject/base-ui/constants'

为什么会这样? 为什么我可以使用此路径选项从位于 baseUrl 之外的简单 TS 文件中导入非常基本的 classes 并在编码时应用它们。而且它们在构建最终应用程序时也不会导致编译器错误!这些应用程序之后按预期工作。

但是当这段代码应该 运行 在 NodeJS 中本地时它不会编译?!

我还需要设置其他选项吗?

非常感谢任何帮助或提示!

嗯,我自己找到了解决办法。

只需将一个桶 (index.ts) 放入外部文件夹并导出感兴趣的文件即可。所以在我的例子中这样做解决了上面的问题:

theproject
    |___ frontend1/
    |___ frontend2/
    ...
    |___ base-ui/constants/constants.ts
    |___ base-ui/index.ts

index.ts

的内容
export * from './constants/constants';

不幸的是,这适用于 Angular 8.1.3。使用 Angular 8.2.7 运行 的较新项目出现与以前相同的错误...