Skip to content

tsconfig "paths" config is not recognized #3837

Closed

Description

@lehresman

Mac OSX Sierra
angular-cli version 1.0.0-beta.24

I'm trying to configure things so I don't have to use ugly (and brittle) relative paths when including modules from my own project. I modified tsconfig.json to include:

  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@app/*": "app/*"
    },
   ...

And that works great for TypeScript.

However, "ng serve" is throwing this error:

ERROR in ./src/app/content/content.component.ts
Module build failed: Error: /Users/lehresman/Projects/gazelle-ui/src/app/content/content.component.ts (2,29): Cannot find module '@app/models/client.model'.)
    at _checkDiagnostics (/Users/lehresman/Projects/gazelle-ui/node_modules/@ngtools/webpack/src/loader.js:116:15)
    at /Users/lehresman/Projects/gazelle-ui/node_modules/@ngtools/webpack/src/loader.js:141:17
 @ ./src/app/app.module.ts 17:0-65
 @ ./src/main.ts
 @ multi main

I've discovered that Webpack has configuration options for this, but I can't figure out how to configure Webpack through Angular-CLI to support this. Is this a bug, or is this feature not exposed?

Activity

  1. ValeryVS commented on Jan 3, 2017

    @ValeryVS
    Contributor

    Are you using ng serve with --aot flag?
    Probably, tsginfig's paths is ofiicialy supported by angular cli only for JIT compile for now.

  2. lehresman commented on Jan 3, 2017

    @lehresman
    Author

    No, just plain ng serve

  3. ValeryVS commented on Jan 3, 2017

    @ValeryVS
    Contributor

    Well, it should work then. I'am use the same config. (But with beta.22 version. Still have not time for update.)
    Make shure, that you restart your ng serve after changing tsconfig.json
    It will not load new settings while serving.

  4. lehresman commented on Jan 3, 2017

    @lehresman
    Author

    Thanks for letting me know that it was supported. I was chasing rabbit trails trying to get angular-cli to support it, but turns out it IS supported already. I simply had my paths wrong.

  5. lehresman commented on Jan 3, 2017

    @lehresman
    Author

    Also, for posterity, I had to make the paths be an array. It looks like Typescript accepts a string, but angular-cli expects it to be an array.

      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@app/*": ["app/*"]  // <-- must be an array
        },
       ...
    
  6. lehresman commented on Jan 3, 2017

    @lehresman
    Author

    Ok, that works fine for the main app, but my tests don't seem to recognize it.

    ng test shows this error:

    ERROR in ./src/app/dashboard/dashboard.component.ts
    Module not found: Error: Can't resolve '@app/services' in '/Users/lehresman/Projects/gazelle-ui/src/app/dashboard'
     @ ./src/app/dashboard/dashboard.component.ts 12:17-41
     @ ./src/app/dashboard/dashboard.component.spec.ts
     @ ./src \.spec\.ts$
     @ ./src/test.ts
    

    ng serve is working fine.

    Here is the dashboard.component.ts

    import { Component, OnInit } from '@angular/core';
    import { AuthService } from '@app/services';
    
    @Component({
      providers: [
        AuthService
      ],
      selector: 'gl-dashboard',
      templateUrl: './dashboard.component.html',
      styleUrls: ['./dashboard.component.scss']
    })
    export class DashboardComponent implements OnInit {
      ngOnInit() {
      }
    
    }
    

    Are the tsconfnig.json baseUrl and paths settings not supported for ng test?

  7. dzonatan commented on Jan 4, 2017

    @dzonatan
    Contributor

    Yes, tests have that issue.
    See #3586 issue. PR #3831 should fix it.

  8. filipesilva commented on Jan 24, 2017

    @filipesilva
    Contributor

    Fixed by #3831, thanks @dzonatan !

  9. Parziphal commented on Aug 5, 2017

    @Parziphal

    Sorry for commenting here, but this isn't working for me. I added baseUrl and paths to tsconfig.json just like the OP posted, but ng build says the module can't be found (it works in the editor, so I guess it's properly configured).

    ng -v says:

    @angular/cli: 1.2.6
    node: 8.2.1
    os: linux x64
    @angular/cdk: 2.0.0-beta.8
    @angular/common: 4.3.2
    @angular/compiler: 4.3.2
    @angular/core: 4.3.2
    @angular/cli: 1.2.6
    @angular/compiler-cli: 4.3.2
    etc...
    
  10. filipesilva commented on Aug 10, 2017

    @filipesilva
    Contributor

    @Parziphal I don't know what's going on in your setup, but if you can reproduce in a new project then I ask you to open a new issue with the reproduction. If it does work there, then have a look at how all the tsconfig.json might differ from yours.

  11. duncanwerner commented on Aug 14, 2017

    @duncanwerner

    I believe this regressed. I had the following setup in [root]/tsconfig.json:

    {
        ...
        "baseUrl": "src",
        "paths": {
          "@local/*": ["../local_modules/*"]
        }
        ...
    }
    

    and then in my files I referenced packages in local_modules using the @local/X alias. That worked in 1.2.3. I just upgraded to 1.3.0, and it fails. Reverting to 1.2.3 resolves it. I'm not sure if this was supposed to work, or if this was just a hack I found in the comments.

  12. ZiruZanrgeiff commented on Aug 14, 2017

    @ZiruZanrgeiff

    Hi, I have the same problem. I am in a fresh project. With this setup:

    @angular/cli: 1.2.6
    node: 6.10.2
    os: darwin x64
    @angular/animations: 4.3.4
    @angular/cdk: 2.0.0-beta.8
    @angular/common: 4.3.4
    @angular/compiler: 4.3.4
    @angular/core: 4.3.4
    @angular/forms: 4.3.4
    @angular/http: 4.3.4
    @angular/material: 2.0.0-beta.8
    @angular/platform-browser: 4.3.4
    @angular/platform-browser-dynamic: 4.3.4
    @angular/router: 4.3.4
    @angular/cli: 1.2.6
    @angular/compiler-cli: 4.3.4
    @angular/language-service: 4.3.4
    

    And after set the paths:

    {
      "extends": "../tsconfig.json",
      "compilerOptions": {
        "outDir": "../out-tsc/app",
        "baseUrl": "./",
        "module": "es2015",
        "types": []
      },
      "exclude": [
        "test.ts",
        "**/*.spec.ts"
      ],
      "paths": {
        "@nexus-shared/*": [
          "app/shared/*"
        ]
      }
    }
    

    I try to run ng serve an I got this error:

    ERROR in /Users/ronildo/dev/v4nexus/nexuscloud-frontend/src/app/app.module.ts (10,30): Cannot find module '@shared/shared.module'.
    
  13. 22 remaining items

  14. seabass223 commented on Nov 8, 2018

    @seabass223

    thanks for the response. I tried "@services*":["app/services*"] but that didn't work either. I'll give the module-resolution handbook a good read.

  15. MarcosMeli commented on Nov 11, 2018

    @MarcosMeli

    Solved the problem in Angular 7 adding the paths to both tsconfig files

    • paths in tsconfig.json helps vscode to works and with intellisense
    • paths in tsconfig.app.json is also needed for angular

    tsconfig.json

    image

    tsconfig.app.json

    image

    and the intellisense works great

    image

  16. seabass223 commented on Nov 12, 2018

    @seabass223

    that does work great since your mapping directly to individual files, but may still fail when using the * wildcard.
    After reading the Module Resolution page, I ran tsc --traceResolution

    'baseUrl' option is set to 'C:/Users/WindowsUsers/source/repos/path-alias-test/src', using this value to resolve non-relative module name '@services'.
    'paths' option is specified, looking for a pattern to match module name '@services'.
    Module name '@services', matched pattern '@services'.
    Trying substitution 'app/services/*', candidate module location: 'app/services/*'.
    Loading module as file / folder, candidate module location 'C:/Users/WindowsUsers/source/repos/path-alias-test/src/app/services/*', target file type 'JavaScript'.
    File 'C:/Users/WindowsUsers/source/repos/path-alias-test/src/app/services/*.js' does not exist.
    File 'C:/Users/WindowsUsers/source/repos/path-alias-test/src/app/services/*.jsx' does not exist.
    Directory 'C:/Users/WindowsUsers/source/repos/path-alias-test/src/app/services/*' does not exist, skipping all lookups in it.
    Loading module '@services' from 'node_modules' folder, target file type 'JavaScript'.
    Directory 'C:/Users/WindowsUsers/source/repos/path-alias-test/src/app/node_modules' does not exist, skipping all lookups in it.
    Directory 'C:/Users/WindowsUsers/source/repos/path-alias-test/src/node_modules' does not exist, skipping all lookups in it.
    File 'C:/Users/WindowsUsers/source/repos/path-alias-test/node_modules/@services.js' does not exist.
    File 'C:/Users/WindowsUsers/source/repos/path-alias-test/node_modules/@services.jsx' does not exist.
    Directory 'C:/Users/WindowsUsers/source/repos/node_modules' does not exist, skipping all lookups in it.
    Directory 'C:/Users/WindowsUsers/source/node_modules' does not exist, skipping all lookups in it.
    Directory 'C:/Users/WindowsUsers/node_modules' does not exist, skipping all lookups in it.
    Directory 'C:/Users/node_modules' does not exist, skipping all lookups in it.
    Directory 'C:/node_modules' does not exist, skipping all lookups in it.
    ======== Module name '@services' was not resolved. ========
    

    I was able to fix it finally by setting my tsconfig (tsconfig.app.json has no baseUrl or Paths because it only extends tsconfig)

     "baseUrl": "src",
      "paths":{
          "@services":["app/services/"]
       },
    

    and appropriately using index.ts files just like node_modules/@angular does.
    The * were the culprit.

  17. localyost3000 commented on Nov 16, 2018

    @localyost3000

    I'm having a similar problem after updating to angular 7.0.4. I do not use angular cli for my project, but I am convinced it is ngtools/webpack causing the problem.

    The relevant portions of my tsconfig look like this:

            "baseUrl": ".",
            "paths": {
                "@components/*": ["components/*", "components/"],
                "@directives/*": ["directives/*", "directives/"],
                "@core/*": ["core/*", "core/"],
                "@guards/*": ["guards/*", "guards/"],
                "@models/*": ["models/*", "models/"],
                "@modules/*": ["modules/*", "modules/"],
                "@pipes/*": ["pipes/*", "pipes/"],
                "@services/*": ["services/*", "services/"],
                "@resolvers/*": ["resolvers/*", "resolvers/"],
                "@mock_data/*": ["tests/mock_data/*", "tests/mock_data/"],
                "@environments/*": ["environments/*", "environments/"]
            }
    

    This builds but with 2 big caveats.

    1. Circular dependency errors for any service which imports another service, since the both resolve to @services/index`
    2. All top level imports have to use @services/* instead of just @services/

    I've run tsc -p ./tsconfig.app.json --traceResolution a couple dozen times and grepped for the paths which were throwing errors in the angular build, and all of them are resolving to the right file through tsc.

    I'm not sure why this changed between 6 and 7, since there was no mention of any changes around tsconfig in any of the Changelogs. Anyone else still stuck after following the advice in this thread?

  18. MarcosMeli commented on Nov 16, 2018

    @MarcosMeli

    @seabass223 it works for me with * wilcard with no problems but only if I duplicate paths in tsconfig.json and tsconfig.app.json

    image

    and the imports works fantastic

    image

  19. localyost3000 commented on Nov 16, 2018

    @localyost3000

    Super quick update:

    With the same tsconfig.json I posted above, I was able to get it to build, with no circular dependencies and no stars in the path. I did a global Find and replace for all imports ending in / and replaced them all with /index. This should be default behavior, and tsc resolves without the index, but by adding it, angular compiles fine.

    I'm not super happy with this resolution, but once the Angular team fixes this issue, it should be pretty easy to do another find and replace to remove the /index in every file.

  20. luckylooke commented on Dec 10, 2018

    @luckylooke
  21. gogakoreli commented on Jan 16, 2019

    @gogakoreli

    In my case tsconfig.spec.json was overwriting baseUrl

  22. anilvangari2005 commented on Feb 8, 2019

    @anilvangari2005

    I commented out baseUrl property in tsconfig.app.json and now everything works including intellisense and ng serve.
    Previously intellisense worked but ng serve failed with "Cannot find module" errors.

    tsconfig.json:

    "baseUrl": "./",
    "paths": {
      "@services/*": ["src/app/components/services/*"],
      ...
    }
    

    tsconfig.app.json relevant config

    "compilerOptions": {
      "outDir": "../out-tsc/app",
      //"baseUrl": "./",
      "module": "es2015",
      "types": ["highcharts"]
    },
    
    
  23. anikets43 commented on Feb 24, 2019

    @anikets43

    I have a problem similar to this when I run the tests E2E

    Angular CLI version:

    Angular CLI: 1.7.3
    Node: 8.9.1
    OS: linux x64
    Angular: 5.2.9
    ... animations, common, compiler, compiler-cli, core, forms
    ... http, language-service, platform-browser
    ... platform-browser-dynamic, router
    
    @angular/cli: 1.7.3
    @angular-devkit/build-optimizer: 0.3.2
    @angular-devkit/core: 0.3.2
    @angular-devkit/schematics: 0.3.2
    @ngtools/json-schema: 1.2.0
    @ngtools/webpack: 1.10.2
    @schematics/angular: 0.3.2
    @schematics/package-update: 0.3.2
    typescript: 2.7.2
    webpack: 3.11.0
    

    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"
            ],
            "baseUrl": ".",
            "paths": {
                "@service/*": ["src/app/shared/service/*"],
                "@directive/*": ["src/app/shared/directive/*"],
                "@component/*": ["src/app/shared/component/*"],
                "@entity/*": ["src/app/entity/*"],
                "@enum/*": ["src/app/enum/*"],
                "@environment/*": ["src/environments/*"],
                "@shared/*": ["src/app/shared/*"],
                "@guest/*": ["src/app/guest/*"],
                "@dashboard/*": ["src/app/dashboard/*"],
                "@validator/*": ["src/app/validator/*"],
                "@interface/*": ["src/app/interface/*"],
                "@mask/*": ["src/app/mask/*"],
                "@pipe/*": ["src/app/shared/pipe/*"],
                "@e2e/*": ["e2e/*"],
                "@factory/*": ["factory/*"],
                "@mock/*": ["mock/*"],
                "@database/*": ["database/*"]
            },
            "lib": [
                "es2017",
                "dom"
            ]
        }
    }
    

    tsconfig.e2e.json

    {
        "extends": "../tsconfig.json",
        "compilerOptions": {
            "outDir": "../out-tsc/e2e",
            "module": "commonJS",
            "types": [
                "jasmine",
                "jasminewd2",
                "node"
            ]
        }
    }
    

    Error: Error: Error: Cannot find module '@e2e/utils/utils'

    @ivanguimam Did you find solution for this?

  24. danielpcampagna commented on Feb 27, 2019

    @danielpcampagna

    I am having trouble getting paths to work when building packages. ie in the tsconfig.lib.json
    I have added:

    "paths": {"@lib/*": ["lib/*"], },
    

    to tsconfig.lib.json and then try to utilise it with a path such as

    import { CrossfilterDataComponent } from "@lib/bids/crossfilter-data/crossfilter-data.component";
    

    the target file is src/lib/bids/crossfilter-data/crossfilter-data.component.ts

    @Bengreen I have the same problem. Did you find the solution?

  25. skwny commented on Jul 23, 2019

    @skwny

    Came here b/c I just experienced this same issue. I pieced together a work around from @swimmadude66 solution. For anyone else:

    tsconfig.json compiler options looks like this:

    // tsconfig.json
    "paths": {
      @client/services/*": [
        "src/services/*"
      ]
    }
    

    When importing a service anywhere, I do this:

    // somewhere in the app
    import { Auth_Service } from '@client/services/index';
    

    index.ts is located in the services dir, and contains:

    // index.ts
    export { Auth_Service } from './auth.service';
    export { Loading_Service } from './loading.service';
    export { Store_Service } from './store.service';
    

    There are no more circular dependency warnings after this.

  26. veerabhadraraochikka commented on Jul 31, 2019

    @veerabhadraraochikka

    I commented out baseUrl property in tsconfig.app.json and now everything works including intellisense and ng serve.
    Previously intellisense worked but ng serve failed with "Cannot find module" errors.

    tsconfig.json:

    "baseUrl": "./",
    "paths": {
      "@services/*": ["src/app/components/services/*"],
      ...
    }
    

    tsconfig.app.json relevant config

    "compilerOptions": {
      "outDir": "../out-tsc/app",
      //"baseUrl": "./",
      "module": "es2015",
      "types": ["highcharts"]
    },
    

    while migration from mono app to multi app we should look at baseurl in tsconfig.json

  27. angular-automatic-lock-bot commented on Sep 9, 2019

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  28. locked and limited conversation to collaborators on Sep 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions