Avoiding relative paths in Angular CLI

后端 未结 7 1052
-上瘾入骨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:30

    Thanks to jonrsharpe's answer for pointing me in right direction. Although, after adding the paths, as defined in answer, I was still not able to make it work. For anyone else facing same problem as me in future, here's what I did to fix the issues.

    I have a shared module and its services are being used in multiple components, so...

    tsconfig.json:

    {
        "compilerOptions": {
            ...
            "baseUrl": ".", //had to add this too
            "paths": {
                "@shared/*": ["src/app/modules/shared/*"]
            }
        }
    }
    

    After this, VS Code was able to resolve the import but I still got following error from webpack while compilation.

    Module not found: Error: Can't resolve

    To fix this I had to add

    1. baseUrl of tsconfig in webpack's resolve.modules
    2. paths of tsconfig in webpack's resolve.alias

    webpack.config.js:

    resolve: {
      extensions: ['*', '.js', '.ts'],
      modules: [
        rootDir,
        path.join(rootDir, 'node_modules')
      ],
      alias: {
        '@shared': 'src/app/modules/shared'
      }
    },
    

    component.ts:

    import { FooService } from '@shared/services/foo.service'
    import { BarService } from '@shared/services/bar.service'
    import { BazService } from '@shared/services/baz.service'
    

    To make it even more cleaner, I added an index.d.ts inside services folder and exported all my services from there, like this:

    index.d.ts:

    export * from './foo.service';
    export * from './bar.service';
    export * from './baz.service';
    

    and now inside any component:

    import { FooService, BarService, BazService } from '@shared/services';
    
    0 讨论(0)
提交回复
热议问题