Typescript: Problem finding modules for starter project

Created on 15 Aug 2016  路  46Comments  路  Source: microsoft/TypeScript

From @jankalfus August 10th

Sometimes when I open my project, VS Code is unable to find imported external modules. I've got typings for the modules installed, all files in the project compiles fine using tsc, but I get red squiggly lines in the editor. The weird thing is that I get the squiggly lines only for some .tsx files, while it works for others.

The file src/web/App.tsx is fine:
web

While I get squiggly lines for the file src/native/App.tsx:
native

My tsconfig.json content is the following:

{
    "compilerOptions": {
        "allowSyntheticDefaultImports": false,
        "jsx": "react",
        "noImplicitAny": true,
        "experimentalDecorators": true,
        "module": "commonjs",
        "target": "es5",
        "rootDir": "src"
    },
    "exclude": [
        "node_modules",
        "src/native",
        "app",
        "app-native",
        "tools",
        "test"
    ]
}

Both react and react-native are installed as global typings.

Unfortunately, I cannot post the source code right now, but basically, the structure of the source files is as following:

src
 |-- common
 |-- native
       |-- index.ts
       |-- App.tsx
 |-- web
       |-- App.tsx
 |-- index.ts (this one is for web)
  • VSCode Version: 1.4.0
  • OS Version: Windows 10

Any ideas?

Bug Needs More Info VS Code Tracked

Most helpful comment

The tsconfig.json settings are usually the source of the problem: https://www.typescriptlang.org/docs/handbook/compiler-options.html

  • module sets the output type for your code
  • moduleResolution sets the way Typescript tries to look for your modules

moduleResolution should be set to 'node' so that it resolves _/node_modules/_ dependencies properly. Typescript might use this setting automatically depending on what module is set to, but you should set it explicitly to ensure it's correct.

More info on module resolution here: https://www.typescriptlang.org/docs/handbook/module-resolution.html

All 46 comments

From @jankalfus August 10th

I have noticed that if I use File -> Close folder and then File -> Open Folder... and open the project folder again, the errors are gone. If I just restart VS Code instead, I keep getting the errors. I presume that some internal cache gets cleared?

From @jankalfus August 10th

More to this issue: I get the errors every time I create a new folder and ts/tsx file inside. Unfortunately, the workaround I've suggested in the previous comment doesn't work.

From @jankalfus August 10th

I've published the source code. To reproduce this issue:

  1. Go to https://github.com/gina-system/react-starter
  2. Use the steps in the quick start section of the readme
  3. Open the src/native/App.tsx file.

From @waderyan August 10th

I have reproduced this per @jankalfus's instructions.

I'm seeing a "Cannot Find Module" when I hover over react-native

image

Developer shows a seemingly unrelated error.

image

It seems like typings directory is configured correctly.

image

From @waderyan on August 10th

Ok this is strange... I reopened the project to grab another screen shot and this is what I saw.

image

Everything looks good now.

I retraced my steps.

  1. re-cloned https://github.com/gina-system/react-starter in a separate dir.
  2. followed the README steps (npm install, typings install)

Looks good again.

I have this same issue. Not with React, but with any new module that I make.

captura de pantalla

I had experienced the same issue. Perhaps this can provide additional clues:

  • Adding <reference path=""> in a completely separate .ts file worked for a while. I have 1 file with all references I needed and that worked until recently.
  • Adding a <reference path=""> in the file that is having issues always solves the problem. This has been my workaround.
  • There is no pattern I can see when it happens. Files in the same folder may work or not. No apparent "order" seems to trigger it (alphabetical order, folder order, etc). No specific particular module seems to cause it although I had more issues with 'react'.
  • tsc does not report issues. Just VS Code.

I'm having a similar problem, see the attached screenshot showing two files in the same folder of the same project, one of which shows the problem while the other is working correctly. I had no such problem until today, so it's hard to tell what triggers the bug.

image

I have the same issue for "react" when following the steps in https://www.typescriptlang.org/docs/handbook/react-&-webpack.html
As @fabiom mentioned, having (in my case) <reference path="../../typings/tsd.d.ts" /> in at least one file makes the problem go away, in VS Code.
Here are the two files open, both before and after removing "reference path".
vscode-ts

TSC on the other hand, compared to fabiom's comment, report errors when "reference path" is completely removed:
src/components/Hello.tsx(1,24): error TS2307: Cannot find module 'react'. src/components/Hello.tsx(7,16): error TS2602: JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist. src/components/Hello.tsx(7,16): error TS7026: JSX element implicitly has type 'any' because no interface 'JSX.IntrinsicElements' exists src/components/Hello.tsx(7,37): error TS2339: Property 'props' does not exist on type 'Hello'. src/components/Hello.tsx(7,63): error TS2339: Property 'props' does not exist on type 'Hello'. src/components/Hello.tsx(7,80): error TS7026: JSX element implicitly has type 'any' because no interface 'JSX.IntrinsicElements' exists src/index.tsx(1,24): error TS2307: Cannot find module 'react'. src/index.tsx(2,27): error TS2307: Cannot find module 'react-dom'. src/index.tsx(7,5): error TS2602: JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist.

Any plans to fix this ?

f1 -> reload windows = workaround. :P

EDIT: @harshil93 sorry. It's F1. The windows reloading, restart the resolver server.

@michaeljota Not working for my typescript react files.

So this is still an unsolved problem?

I don't know if this still as unsolved problem, but the main workaround here it's to restart the resolver serve. There is one extension that can do it automatically, and manually. typescript-hero. This will only works with VSCode, and it has to be seen as is, a workaround. So this issue should remain open.

/cc @harshil93 @roblom Hope you find this useful.

I tried all the repro instructions listed, none reproed for me. Do people still have this issue?

I was having a similar issue, but could resolve it by adding "types" field to package.json of the imported package to specify corresponding *.d.ts file explicitly. (See http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)
Looks it happens when

  • trying to import a library compiled with old version of TypeScript without "types" field in package.json
  • noImplicitAny=true

This happens to me frequently if I have a pre-existing project that I later want to add typescript to. My assumption would be that VSCode, or the language services, are caching things somewhere and don't get updated.

In my most recent case, this happened when trying to create a redux reducer. import { Record } from 'immutable'; was the problem import, even though tsc --traceResolution path/to/file.ts found it eventually:

======== Module name 'immutable' was successfully resolved to '$HOME/my-project/node_modules/immutable/dist/immutable-nonambient.d.ts'. ========

When this happens, I push my changes to git, delete the directory completely, clone it again into a slightly different path, vscode new/path/, and it's no longer a problem. Granted, this is not an actual solution, but is the most complete information I can provide.

same thing happening to me right now with module electron-updater

@hysaq @mschnee @farfromrefug do you mind sending a small repro project to help investigate? Thanks

Edit your "tsconfig.json" with "noImplicitAny": false

@waderyan, @jankalfus, @michaeljota, @roblom,@hysaq @mschnee @farfromrefug, @dhruvdutt, can you link to a minimal repro in a github repo that showcases the issue? Please create the repo with the exact code one would need to see the issue upon opening the directory in vscode (ie: all node_modules are already installed, as it seems there may be a module versioning issue at play).

Without an explicit repro, we can't make progress on getting a fix in.

I'm seeing something similar. It may not be exactly the same, but it seems like the error codes don't refresh in a predictable manner. do we always have to close the entire folder and re-open it to trigger a refresh? I recorded a video to show the behavior: https://youtu.be/rBnS45DDe3c

i.e. if I add

import * as path from "path";

but I don't have @types/node in my package.json, I get a module not found error.

If I do a npm install --save @types/node. And I go back to the file where I added the import, it still has the squiggle, unless I close the file and re-open it -- or if I make a change to the file -- or do F1-> reload window as previously suggested. It seems like something else ought to trigger the validation -- maybe focus change?

@bkbonner It would definitely take some time initially for TypeScript to understand the definitions file and linking it with the project. Not a bummer!

@dhruvdutt. I don't understand what you mean in your email.

@bkbonner Try waiting for some time after installing npm modules. The compiler may be slow.
When you import a module, what happens behind the scenes is the TypeScript compiler goes to node_modules folder, finds the library and checks for "typings" attribute inside package.json.

@aozgaa I still this with one of my projects which has a 2 package.json structure
this should show the issue.
If in app/package.json i include a package which comes with typings then typescript wont find it (tsconfig.json being in ./)
I tried playing around with tsconfig.json with no success

I'm having this same issue and I think the problem is with tslint and/or the vscode plugin for tslint.

In my case, I'm coding with VSCode and the plugin tslint.

I'm not sure if all cases posted here have no-unused-variable enabled with tslint.

Has anybody noticed that this issue only happens if we enable no-unused-variable on the tslint.json.

The repo gina-system/react-starter has it enabled.

Anybody else could confirm if removing the no-unused-variable the warnings are gone?

Also, the warning happens for any npm library, which is any module without the . for local files, for example, react and angular:

screen shot 2017-08-17 at 12 01 18 pm

My Solution:

If you enable tslint-language-service with the new plugin TSLint (vnext) it seems that fixes the issue.

PS: Be aware both the tslint-language-service and the plugin TSLint (vsnext) are in beta(work in progress), but they seem to be working fine to me.

UPDATED
Actually, it didn't work. I still have the warnings and they are very unstable

If in app/package.json i include a package which comes with typings then typescript wont find it (tsconfig.json being in ./)

@farfromrefug the module resolution logic in the compiler follows that of node. for a tsconfig.json at the root, it will not be able to see node_modules under app\node_modules. consider using path mapping.

This issue has diverged into different directions. does not seem we have any repros for the original issue. closing for now. please file new issue, provide a sample repor or a tsserver log for investigations.

@mhegazy that makes sense, i will look at path mapping. Thanks

Had this same issue this morning. f1 > reload window got rid of the red squiggles for me. Not sure for how long though. (thanks @michaeljota )

@ChrisDillinger Mohamed said:

This issue has diverged into different directions. does not seem we have any repros for the original issue. closing for now. please file new issue, provide a sample repor or a tsserver log for investigations.

Adding to this issue is not productive (especially considering you didn't provide the requested information).

Moving the module to dependencies instead of devDependencies fixed the issue for me. Not really where I want it but works.

I am still experiencing this issue. Every time I create a new file vscode has difficulty recognizing the existence of modules.

@Giwayume please file a new issue and give us some context to be able to reproduce the problem locally.

The tsconfig.json settings are usually the source of the problem: https://www.typescriptlang.org/docs/handbook/compiler-options.html

  • module sets the output type for your code
  • moduleResolution sets the way Typescript tries to look for your modules

moduleResolution should be set to 'node' so that it resolves _/node_modules/_ dependencies properly. Typescript might use this setting automatically depending on what module is set to, but you should set it explicitly to ensure it's correct.

More info on module resolution here: https://www.typescriptlang.org/docs/handbook/module-resolution.html

I don't even understand why the config is necessary for input files. TypeScript should figure everything out on its own.

If you are starting a new application and you just need a couple of files, sure, the compiler wouldn't need a config. But I really don't see a real scenario where the compiler wouldn't need a config file.

The compiler does not know how your project is designed, is it a simple browser js file with types? Is it a node module? Is it another kind of module?

And there is no way for the compiler to know what you want to do with that.

Do you want to target es5? es3? esNext?

I don't know how the compiler should figure everything out.

I'm not saying it should figure _everything_ out. I'm just saying it could figure out everything regarding module structure the input files are using.

Being not very programmer friendly and buggy is one of the reasons I stopped using TypeScript. Babel could be used by a 5 year old, but the same is not true for TypeScript, unfortunately :/

I wasn't going to respond, but somehow I fell that if I don't you will get the felling that you are right, and you are not. A comparison between Babel and Typescript is not only about what is the easier to used, because at the end, Babel is only a transpiler, and Typescript is a complete language. But is not only about that I think.

Babel no longer have presets includes, so no batteries, no fun. You need to include the presets you want to use, and then configure them. While is true that this allow you more control about what you want to use, your point is exactly the opposite.

Babel does not have a type checking system. This is just something that Babel is not. You could, however, use Flow. For sure. But, then you have to configure Flow. And Flow 3rd party libraries. And the Babel-Flow integration.

And what do you mean with buggy anyway? I do have encounter some really edgy bugs, but they all have been reported, and most of them need some underwork first, like conditional typing, that 2.8 have.

So, I'm sorry if you fell Typescript can't be used for a 5 years old, but I don't fell like a 5 years old should program with type checkers, maybe with blocks, but not type checkers.

EDIT: I won't answer you anymore. If you don't use Typescript, I don't even know why you are here, but trolling.

@michaeljota You totally missed my point, again. My point was I don't see a reason why TypeScript couldn't figure out what module structure I'm using automatically.

@jankalfus

Did you read the documentation regarding resolution? The default now is 'node' which should automatically resolve modules as expected when using npm, however the older setting (and the reasons when it is enabled) is for backwards compatibility.

If you're starting with a new project, then everything will work fine, but in case you have a different setting for module or have an older project, there will be some extra config needed. Either way I recommend explicitly setting the option to 'node'.

Perhaps Typescript defaulting to 'classic' resolution mode when the output mode is set to ES6 modules was the wrong choice, but it's all clearly described in the docs. I don't think reading documentation for the compiler settings is very onerous considering the complexity of Typescript in general and the features it provides.

@manigandham Thanks for this explanation.

I still don't see a reason TypeScript couldn't look at first few lines of some file in a project and try to guess what is the module structure being used.

My experience is been that systems that "guess" are far more confusing than those that don't. You shuffle a few trivial lines around, the "guess" becomes wrong and the behavior changes, wat? We're not trying to be Clippy here - It looks like you're using ES6 modules, should I change the module resolution algorithm for you?

If TypeScript had an "auto" module resolution option as default, informed about what type it selected, and the user had the ability to override it manually, what would be confusing about that?

"Auto" is already basically the default - the "classic" resolution algorithm is specifically designed to have the best chance of finding a module in the right place without incorrectly finding modules it shouldn't.

Was this page helpful?
0 / 5 - 0 ratings