如何在angular-cli中为长路径制作"别名"?

man*_*dos 10 angular-cli angular

我正在使用Angular CLI.如何转换路径:

import {AppConfig, AppConfigInterface} from '../../../app.config';
Run Code Online (Sandbox Code Playgroud)

类似于:

import {AppConfig, AppConfigInterface} from 'root/app.config';
Run Code Online (Sandbox Code Playgroud)

小智 18

在tsconfig.json中尝试这个:

  {
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ],
    "paths": {
      "@services/*": ["app/services/*"] // here!
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 你在Angular 7上有这个工作吗?“如果不指定'--baseUrl'选项,则不能使用选项'paths'。” 即使指定了baseUrl选项,路径别名也不起作用。“无法找到模块'@ services /'。这在角度6中工作正常。 (3认同)

Abu*_*ood 7

我想提请注意的是,仅编辑tsconfig.json将对代码完成和通过 ts 编译器进行构建有效。然而,只要您没有在tsconfig.app.json. ng 服务将显示构建error TS2307: Cannot find module '@...

然而,将定义限制为后者将使 ts IntelliSense 编译器将它们显示为无法识别的路径

tsconfig简而言之:定义JSONtsconfig.app文件中的路径

  • 这非常有帮助。可以通过添加_how_来定义每个路径中的路径来改进它。那么这将是最热门的答案。就目前而言,它必须与其他内容结合起来才能发挥作用。 (3认同)

god*_*rry 5

我在尝试解决时发现了这个问题scss我发现由于这个问题,当前的方法将不起作用

解决方法是添加stylePreprocessorOptions到,.angular-cli.json以便它将解析目录中的所有样式

{
    "apps": [{
        ...
        "stylePreprocessorOptions": {
            "includePaths": [
                "./app/global-styles"
            ]
        },
        ...
    }]
}
Run Code Online (Sandbox Code Playgroud)

对于服务器端渲染,您需要为主ssr应用程序构建添加此内容 - 否则您将得到NodeInvocationException: Prerendering failed because of error: Error: Cannot find module 'C:\Users\...\ClientApp\dist-server\main.bundle.js'

{
    "apps": [{
            ...
            "outDir": "dist",
            "stylePreprocessorOptions": {
                "includePaths": [
                    "./app/global-styles"
                ]
            },
            ...
        },
        {
            ...
            "name": "ssr",
            "outDir": "dist-server",
            "stylePreprocessorOptions": {
                "includePaths": [
                    "./app/global-styles"
                ]
            },
            ...
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)