Avoiding relative paths in Angular CLI

后端 未结 7 1058
-上瘾入骨i
-上瘾入骨i 2020-11-30 20:54

I\'m using the latest Angular CLI, and I\'ve created a custom components folder which is a collection of all components.

For example, TextInputComponent

7条回答
  •  暖寄归人
    2020-11-30 21:17

    Keeping it simple

    Let's keep this simple with just a few things you need to know to be able to apply this solution to any future project.

    Preface: Angular doesn't set up the "usual" @/ or ~/ path mappings, probably because it chose to be less opinionated on this matter.

    It does however set a baseUrl for all imports: ./ (which means the folder that tsconfig.json is located in).

    Which then means that any non-relative imports (those that don't start with ./ or ../) are automatically prefixed by the baseUrl.

    So as long as you use paths that start at this base URL for your imports, you should already have a solution! You shouldn't have problems with refactoring as long as your refactoring tool recognizes the base URL and is able to correctly apply import path refactoring.

    So by default, with an unmodified TS config, your can use this kind of import and not worry about relative paths becoming a headache to manage:

    // sample import taking into consideration that there is
    // a baseUrl set up for all imports which get prefixed to
    // all imports automatically:
    
    import { ComingSoonComponentModule } from 'src/app/components/coming-soon/coming-soon.module';
    

    Another solution

    But if you really want to use something like a @/ prefix, you can just as easily do that with a simple path mapping, like this:

    // tsconfig.json
    
    {
      // ...
      "compilerOptions": {
        "baseUrl": "./",
        // notice that the mapping below is relative to the baseUrl: `src/app/*` is in fact `{baseUrl}src/app/*`, ie. `./src/app/*`.
        "paths": { "@/*": ["src/app/*"] },
        // ...
      },
      // ...
    }
    

    Then you can import as either one of these:

    import { ComingSoonComponentModule } from 'src/app/components/coming-soon/coming-soon.module';
    import { ComingSoonComponentModule } from '@/components/coming-soon/coming-soon.module';
    

    Things to remember:

    1. paths tsconfig option is relative to baseUrl option (so keep in mind and use relative paths for the paths keys).
    2. * - the star is the specified module path (as per your specification in code, where you import), everything else is a prefix or suffix to be added, as per your specification in tsconfig, to the final path.

提交回复
热议问题