【问题标题】:How to make an “alias” for a long path in angular-cli?如何在 angular-cli 中为长路径制作“别名”?
【发布时间】:2017-05-21 06:48:48
【问题描述】:

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

import {AppConfig, AppConfigInterface} from '../../../app.config';

类似于:

import {AppConfig, AppConfigInterface} from 'root/app.config';

【问题讨论】:

标签: angular angular-cli


【解决方案1】:

我想提请注意,仅编辑 tsconfig.json 将在代码完成和通过 ts 编译器构建时有效。但是,只要您没有在tsconfig.app.json 中定义它们,Agular-CLI 就无法识别到真实路径的已定义地址。 ng serve 将显示 build error TS2307: Cannot find module '@...

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

简而言之:在tsconfigtsconfig.app JSON 文件中定义路径

【讨论】:

  • 这很有帮助。它可以通过添加 如何 来定义每个路径来改进。那么这将是非常好的答案。就目前而言,它必须与其他组合才能有用。
【解决方案2】:

我在尝试解决scss 时发现了这个问题。由于issue

,我发现当前的方法不起作用

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

{
    "apps": [{
        ...
        "stylePreprocessorOptions": {
            "includePaths": [
                "./app/global-styles"
            ]
        },
        ...
    }]
}

对于服务器端渲染,您需要为 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"
                ]
            },
            ...
        }
    ]
}

【讨论】:

  • 如何从.scss 文件中引用这些全局样式?
  • 据我记得它应该作为@import utils.scss 工作,它将从global-styles 目录导入
【解决方案3】:

在 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!
    }
  }
}

【讨论】:

  • 你有这个在 Angular 7 上工作吗? “如果不指定 '--baseUrl' 选项,则无法使用选项 'paths'。”即使指定了 baseUrl 选项,路径别名也不起作用。 “找不到模块'@services/'。这在 Angular 6 中运行良好。
  • @seabass 你找到 angular 7 的解决方案了吗?
  • 是的,我现在使用 Angular 8,但也可以使用 7。 tsconfig.json "baseUrl":"projects/myproject/src" "paths": { "@services": ["app/modules/services/"] }
【解决方案4】:

angular cli 默认模块目录在 /angular-cli.json 中定义 如果你需要root,你可以试试'/app.config'

【讨论】:

    猜你喜欢
    • 2019-03-03
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2016-06-21
    • 2022-08-06
    • 2022-08-08
    相关资源
    最近更新 更多