angular-cli icon indicating copy to clipboard operation
angular-cli copied to clipboard

tsconfig paths and module resolution errors in VS Code

Open SpiraMira opened this issue 9 years ago • 42 comments

Bug Report or Feature Request (mark with an x)

- [x] bug report -> please search issues before submitting
- [ ] feature request

Versions.

@angular/cli: 1.4.9 node: 7.9.0 os: darwin x64 @angular/animations: 4.4.5 @angular/common: 4.4.5 @angular/compiler: 4.4.5 @angular/core: 4.4.5 @angular/forms: 4.4.5 @angular/http: 4.4.5 @angular/platform-browser: 4.4.5 @angular/platform-browser-dynamic: 4.4.5 @angular/router: 4.4.5 @angular/cli: 1.4.9 @angular/compiler-cli: 4.4.5 typescript: 2.3.4

macOS Sierra 10.12.6 VS Code 1.17.2

Repro steps.

My tsconfig path property seems broken. When I replace my path mapped imports (@shared, @assets etc.) with the equivalent coded relative paths, typescript module resolution seems to work (vs code intellisense is happy) I have a large angular 2 project and am used to aliasing my asset and shared directories this way. NOTE: project builds and (seems) to run just fine This has been reported often, but I can't make sense of the current state of this issue. This more than annoying as VS Code reports Angular spurious errors on all of my components. I also suspect this is why I get the infamous Can't read property isSkipSelf of null when I open my templates (html) in VS Code. I was running 1.4.2 and just tried ~1.4.2, which resolves to 1.4.9 in my package.json, to no avail. Will 1.5.x fix this? How can I help debug this without providing a copy of my app?

Thanks in advance. Regards.

The log given by the failure.

Desired functionality.

Mention any other details that might be useful.

SpiraMira avatar Oct 21 '17 08:10 SpiraMira

vscode seem to only look into nearest tsconfig.json file, while angular read your tsconfig.app.json You should add relative path config to both tsconfig.json and tsconfig.app.json.

Neither this

This works for me:

Move (or repeat) paths section from tsconfig.app.json to tsconfig.json

Nor this is a valid solution for the problem for the current "monorepo"-approach.

If we have multiple projects in one repo, the determination for a "project" in the context of angular is done by tsconfig files. Now imagine that you have 3 projects A & B & C, while B & C being a library project. As a good developer you want a clean separation between your concerns in such architecture / structure:

  • Project A depends on B & C, therefore it has a mapping to C and to B
  • Project B knows nothing about C & A
  • Project C knows nothing about B & A

You are going to solve this by adding the mapping into the tsconfig of the Project A and not in the root tsconfig of the repo, otherwise you would create a relation/mapping what you actually don't want..

We too suffer from this bug. At first I was thinking this is a bug in Webstorm, but after discovering this thread things got interesting.

flash-me avatar Nov 10 '18 14:11 flash-me

Yeah we've the same problems, we've added two angular projects in the same repo and we've two different tsconfig files, because different apps require different alias. the app is compiling and running fine but VSCode highlight every import in red, and the intellisense for paths is broken

kurtommy avatar Nov 11 '18 23:11 kurtommy

Not sure if this'll help anyone but a colleague was getting this problem because he was opening his project (Open Folder) at a level below the project root (e.g. /src). Problem solved by closing and re-opening at the project root.

sherwopj avatar Jan 04 '19 09:01 sherwopj

it's all inside the angular.json file. the vscode should pick the tscofnig based on the sourceRoot option in the angular.json a sample angular json look like this

"playground-wp": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.wp.json",
            "polyfills": "src/polyfills.ts",
            "stylePreprocessorOptions": {
              "includePaths": [
                "src/.lib"
              ]
            },
            "assets": [
              "src/assets",
              "src/favicon.ico"
            ],
            "styles": [
              "node_modules/nebular-icons/scss/nebular-icons.scss",
              "src/styles.scss"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]
            }
          }
        },
    }

in here the playground-wp.sourceRoot is define the project root folder, so when we are in this folder, the vscode should pick the playground-wp.architect.build.options.tsConfig which is src/tsconfig.wp.json

tsconfig.wp.json have a link back to the parent tsconfig an example is like this:

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

which extend the parent tsconfig.json

mhamri avatar Jan 08 '19 03:01 mhamri

Simply restarting VSCode fixed this issue for me after updating the paths in tsconfig.json.

erjdev avatar Jan 16 '19 02:01 erjdev

it's all inside the angular.json file. the vscode should pick the tscofnig based on the sourceRoot option in the angular.json

I wouldn't say that vscode has to adapt / consider the angular.json, since this is something angular related. This would mean vscode needs to know where to lookup based on the specific config for every framework / library out there. Jeezz...

We were able to get rid of this after we switched to the jest framework for unit testing. Now we have one tsconfig.json file in every project root and one for jest in the repo root, since we are using the same config for all unit tests. The only drawback is that we can't extend the configs from the repo root one. But I'd rather have this instead of missing IDE and autocomplete features, false positives etc..

flash-me avatar Jan 19 '19 16:01 flash-me

We use non-standard names for the each project tsconfig because there are files for two different compilations contexts side by side in the same folder. These are your app TS files, and your unit test TS files.

The unit test files have different typings available (jasmine, node) that really shouldn't be valid in the app files. The app and unit tests also have different files/include/exclude arrays. So as far as compilation units are concerned, these definitely need to be different files.

What we did at the time was have a single top-level tsconfig file that was extra permissive, and local configs with different names on purpose so they weren't caught by the editor. This way you wouldn't get errors in your editor when you tried to use jasmine helpers in your unit tests.

At the time there weren't a lot of Angular CLI based monorepos and that solution seemed good enough.

Now there are more. I think the strictly correct approach for these cases is to:

  • keep the toplevel tsconfig.json as is
  • add a new tsconfig.json on each project that extends the toplevel one, and contains a paths entry for that project
  • have tsconfig.app.json and tsconfig.spec.json in each project extend the tsconfig.json described above, and not define any paths themselves

So for it would look like this for a new workspace:

src/
--tsconfig.json       // paths go here
--tsconfig.app.json   // no paths here
--tsconfig.spec.json  // no paths here
tsconfig.json	      // no paths here

And for a monorepo style workspace:

projects/
--an-app/
----tsconfig.json
----tsconfig.app.json
----tsconfig.spec.json
--another-app/
----tsconfig.json
----tsconfig.app.json
----tsconfig.spec.json
--and-another-app/
----tsconfig.json
----tsconfig.app.json
----tsconfig.spec.json
tsconfig.json

We didn't do this from the start because it was another file, and we were trying to keep the file count as low as we could. But maybe we should do this now when adding a new project.

filipesilva avatar Jan 28 '19 16:01 filipesilva

Not sure if this'll help anyone but a colleague was getting this problem because he was opening his project (Open Folder) at a level below the project root (e.g. /src). Problem solved by closing and re-opening at the project root.

I had this same problem and found a solution. This is very annoying because I like to have only the highest level directory open that is necessary. If you create a tsconfig.json file (exact name is important) at the same level as where you have vscode open, and create paths relative to that directory, then the lint errors will go away (granted that this was the issue and not that you were setting up your paths wrong initially). So I now have the original tsconfig.json file in my project root directory, another in the src directory, and another in the app directory. Now I can open the project in the src or the app directory without vscode trying to say that the paths don't exist.

If anyone has a better solution to this issue that would be awesome. For reference this is my structure now:

Project Root/ --src/ ----app/ ------tsconfig.json (paths specified relative to this directory) ----tsconfig.json (paths specified relative to this directory) --tsconfig.json (paths specified relative to this directory)

amumm avatar Jan 29 '19 06:01 amumm

We use non-standard names for the each project tsconfig because there are files for two different compilations contexts side by side in the same folder. These are your app TS files, and your unit test TS files. ...... We didn't do this from the start because it was another file, and we were trying to keep the file count as low as we could. But maybe we should do this now when adding a new project.

Sounds valid. But as far as I understand the reason for having separate tsconfig files is due to the different compilation contexts, right? So why keeping those files at all? You could wrap the relevant settings into angular.json and just keep one tsconfig for each project for the IDE's.

You could even extend the cli to have a section "typescriptOptions" which then could have multiple "targets" or "configs" in the same manner like the other build/serve configs:

{
  "projects": {
   ....
   },
   "schematics": {
   ...
   },
   "typescriptOptions": {           // sample name...
      "configurations": {
         "latestChrome": { ... },
         "unitTests": { ... },
      }
   }
}

This could work, don't? At least I'm not aware of any restrictions / blocker for not doing this.

flash-me avatar Jan 30 '19 17:01 flash-me

I'm not a big fan of adding the TS options in the angular.json file to be honest. It makes TS options more opaque because you can't change the file on disk directly, removes the autocomplete for tsconfig that some editors have, and removes interop with other tools.

filipesilva avatar Jan 30 '19 17:01 filipesilva

I don't get it. You can also change the angular.json directly on the fs + one could just extend the json schema to reference the one from tsconfig in order to have autocomplete. Can you give me an example for another tool that uses e. g. tsconfig.app.json etc?

In my example it was intended to leave at least one tsconfig.json and hide the additional ones, because even TypeScript itself has no support for other naming patterns

flash-me avatar Feb 02 '19 19:02 flash-me

I often run tsc -p src/tsconfig.app.json myself, for instance. Or ngc -p src/tsconfig.app.json. You could run other tools that take typescript configuration (like tslint) by pointing it at the file as well.

filipesilva avatar Feb 02 '19 21:02 filipesilva

Okay, but the tool devs have to provide such functionality, nothing out of the box. Can you tell Vscode to use a particular tsconfig for its autocomplete? Or can you configure the angular language service to use another tsconfig? Even if your IDE can handle other naming patterns, how does it know which one to use for a specific folder, if there are multiple tsconfigs. The one for unit tests also include the origin files...

The feedback I'm receiving pretty often is that it's not really clear which of those files is now being used from the IDE while you are developing / doing other tasks.

flash-me avatar Feb 03 '19 11:02 flash-me

Keep it simple, if the vscode found two tsconfig in immediate parent folder, just ask which one to use. And save it in the .vs folder.

Later if user want to change the tsconfig, they should be able to do so by some setting, better if it be a right click menu on folder viewer

On Sun, Feb 3, 2019, 19:17 kqadem <[email protected] wrote:

Okay, but the tool devs have to provide such functionality, nothing out of the box. Can you tell Vscode to use a particular tsconfig for its autocomplete? Or can you configure the angular Lange service to use another tsconfig? Even if your IDE can handle other naming patterns, how does it know which one to use for a specific folder, if there are multiple tsconfigs. The one for unit tests also include the origin files...

The feedback I'm receiving pretty often is that it's not really clear which of those files is now being used from the IDE while you are developing / doing other tasks.

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/angular/angular-cli/issues/8138#issuecomment-460042919, or mute the thread https://github.com/notifications/unsubscribe-auth/AIk0J2eq-cKFKwnky2IkG1pWih3TbTZWks5vJsVNgaJpZM4QBesR .

mhamri avatar Feb 03 '19 12:02 mhamri

I was having troubles with absolute and relative URLs myself; ended up following instructions at https://hackernoon.com/react-pro-tip-use-absolute-imports-for-better-readability-and-easy-refactoring-2ad5c7f2f957 which completely fixed the issues.

TL;DR: Make a .env file in project root and add this: NODE_PATH=src/

Then make a jsonconfig.json file in project root and add this:

{
  "compilerOptions": {
    "baseUrl": "src"
  }
}

I'm actually in a React codebase and don't even use typescript in it, yet setting the "javascript.implicitProjectConfig.checkJs": true in my vscode settings gives me all the intellisense I need with just these two changes!

lifenstein avatar Feb 15 '19 01:02 lifenstein

There are many folders in my VSCode workspace inspector, and VSCode may only use the first folder's tsconfig.json. If your tsconfig.json is not in the first folder, drag the folder to the first and try it again, it worked for me.

So one project one workspace and place the configure folder at first place.

ruojianll avatar Feb 15 '19 04:02 ruojianll

As there is no clear solution, I will past my working one:

folders:
-root
-tsconfig.json #the package config
--src #the source of my package
--demo
--tsconfig.json #the storybook config referencing my upper module as "@sproutch/ui"

Important note

I had to remove "rootDir": "src", from the root package config to make it work.

Here are the full files.

Package config

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "react",
    "lib": ["es2017", "dom"],
    "module": "commonjs",
    "declaration": true,
    "moduleResolution": "node",
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedParameters": true,
    "outDir": "lib",
    "preserveConstEnums": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "target": "es5",
    "types": ["node", "react", "react-dom", "react-native"]
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "build",
    "node_modules",
    "jest.config.js",
    "App.js",
    "babel.config.js",
    "metro.config.js"
  ],
  "compileOnSave": false
}

Storybook subfolder config

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "baseUrl": "../",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "react",
    "lib": ["es2017", "dom"],
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "outDir": "lib",
    "paths": {
      "@sproutch/ui": ["./src"]
    },
    "preserveConstEnums": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "target": "es5",
    "types": ["node", "react", "react-dom", "react-native"]
  },
  "include": [
    "./stories/**/*",
  ],
  "exclude": [
    "./stories/**/*native*",
  ]
}

dagatsoin avatar Feb 18 '19 10:02 dagatsoin

Here is how I fixed it, turns out it is a problem with VSCode. Sometimes changes to tsconfig are not reflected in the IntelliSense. I closed VSCode and made sure no VSCode process was running. They reopened VSCode and Voila! IntelliSense now detects the @ 😩

smaranh avatar Jan 17 '20 18:01 smaranh

https://github.com/microsoft/TypeScript/pull/37239 might help with this. It's described in https://devblogs.microsoft.com/typescript/announcing-typescript-3-9-beta/ as follows:

Support for “Solution Style” tsconfig.json Files ... This file that really does nothing but manage other project files is often called a “solution” in some environments. Here, none of these tsconfig.*.json files get picked up by the server, but we’d really like the language server to understand that the current .ts file probably belonds to one of the mentioned projects in this root tsconfig.json.

TypeScript 3.9 adds support to editing scenarios for this configuration. For more details, take a look at the pull request that added this functionality.

filipesilva avatar Mar 30 '20 08:03 filipesilva

Discussed this in a meeting earlier and tsconfig "solutions" can be a great answer to this problem. We'll do some more investigation to see exactly how this can work and what release we can fit it into.

dgp1130 avatar Apr 09 '20 20:04 dgp1130