154

I've got a simple example project using TypeScript: https://github.com/unindented/ts-webpack-example

Running tsc -p . (with tsc version 1.8.10) throws the following:

app/index.ts(1,21): error TS2307: Cannot find module 'components/counter'.
components/button/index.ts(2,22): error TS2307: Cannot find module 'shared/backbone_base_view'.
components/button/index.ts(3,25): error TS2307: Cannot find module 'shared/backbone_with_default_render'.
components/counter/index.ts(2,22): error TS2307: Cannot find module 'shared/backbone_base_view'.
components/counter/index.ts(3,25): error TS2307: Cannot find module 'shared/backbone_with_default_render'.
components/counter/index.ts(4,27): error TS2307: Cannot find module 'shared/backbone_with_subviews'.
components/counter/index.ts(5,20): error TS2307: Cannot find module 'components/button'.

It complains about all imports of local files, like the following:

import Counter from 'components/counter';

If I change it to a relative path it works, but I don't want to, as it makes my life more difficult when moving files around:

import Counter from '../components/counter';

The vscode codebase does not use relative paths, but everything works fine for them, so I must be missing something in my project: https://github.com/Microsoft/vscode/blob/0e81224179fbb8f6fda18ca7362d8500a263cfef/src/vs/languages/typescript/common/typescript.ts#L7-L14

You can check out my GitHub repo, but in case it helps here's the tsconfig.json file I'm using:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "noImplicitAny": false,
    "removeComments": false,
    "preserveConstEnums": true,
    "sourceMap": true,
    "outDir": "dist"
  },
  "exclude": [
    "dist",
    "node_modules"
  ]
}

Funny thing is, building the project through webpack using ts-loader works fine, so I'm guessing it's just a configuration issue...

Daniel Perez Alvarez
  • 6,570
  • 5
  • 28
  • 27

19 Answers19

168

@vladima replied to this issue on GitHub:

The way the compiler resolves modules is controlled by moduleResolution option that can be either node or classic (more details and differences can be found here). If this setting is omitted the compiler treats this setting to be node if module is commonjs and classic - otherwise. In your case if you want classic module resolution strategy to be used with commonjs modules - you need to set it explicitly by using

{
    "compilerOptions": {
        "moduleResolution": "node"
    }
}
Francis Upton IV
  • 19,322
  • 3
  • 53
  • 57
Daniel Perez Alvarez
  • 6,570
  • 5
  • 28
  • 27
  • 3
    I am seeing this error: `error TS5023: Unknown compiler option 'moduleResolution'.` – SSH This Jun 26 '18 at 20:59
  • Required if you are using `import * as microsoftTeams from "@microsoft/teams-js";` in an static .html which uses `.js` files compiled with `tsc` for MS teams. – ManuelTS Aug 06 '20 at 13:57
  • 117
    I get this error even with moduleResolution = node – Akshay Vijay Jain Apr 18 '21 at 09:26
  • 1
    Visual Studio threw this error because it refused to resolve the include path of a local package. Three hours later, comparing module versions we found that VS did not like some quiet "implicit any" errors within the package. The local builds of the package didn't complain, but VS really did not want to use it. – Benxamin Sep 15 '21 at 23:21
  • 3
    I didn't understand: if I want `classic` I've to set `node`? – Christian Vincenzo Traina May 25 '22 at 12:55
38

In some cases you just need to update the include array.

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "outDir": "dist",
    "sourceMap": false,
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*.ts", "tests/**/*.ts"],
  "exclude": ["node_modules", ".vscode"]
}
codejockie
  • 9,020
  • 4
  • 40
  • 46
  • 3
    Check also your `exclude` property! My problem was that `exclude` was excluding some of my files (of course, this was a mistake). – Matt Sep 20 '21 at 18:03
  • This was the solution for me. I moved `"exclude": [..., "**/*.test.ts"]` to my `tsconfig.build.json` file so that typescript can resolve modules during development, but still exclude test files on build. – Harley Lang Nov 10 '21 at 11:51
  • 5
    `"baseUrl": "."` worked for me – A. Binzxxxxxx Apr 12 '22 at 18:47
20

My problem was building in different environments. In my OSX build there wasn't any problem. But when i try to build on Linux environment, it was failing. The reason behind that was case sensitivity of operating systems. Anyone who suffers from this problem please also check case sensitivity in your imports.

File structure was:

/X/Y.ts

My import was:

import Y from "./x/Y.ts";

So, my fix was just making "x" uppercase.

import Y from "./X/Y.ts";
Can ÖZGEN
  • 238
  • 3
  • 8
  • 10
    This is what the `tsconfig.json` option `forceConsistentCasingInFileNames` protects you from. By setting this option to `true` tsc will give you an error if you import with a different case than what the file actually has, so you can find these problems earlier even if you are on a case-insensitive filesystem. – Jason Kohles Apr 09 '22 at 17:09
  • MY mistake was to omit `.ts` in the import doc and it started working again after adding it. – Lalit Fauzdar May 29 '22 at 09:30
  • Same issue but we had `Index.ts` with a capital "I" – Jaydo Jul 26 '22 at 02:25
  • 2
    Somehow I had both `xx/y.ts` and `xX/z.ts` on the same commit, but only `xX` on the filesystem (OSX). I was able to build locally but the build system that ran on Linux yielded TS2307. I simply rebased amending the commit (unstaged the `xx/y.ts` and staged `xX/y.ts`). – afarah Sep 09 '22 at 15:44
  • 1
    this solved my issue, thanks, I cannot believe it, in TS, this different case will give us this issue. in my case, the issue is only in remote docker pipeline, but it is fully fine locally – tim Jan 05 '23 at 03:45
8

In VS2019, the project property page, TypeScript Build tab has a setting (dropdown) for "Module System". When I changed that from "ES2015" to CommonJS, then VS2019 IDE stopped complaining that it could find neither axios nor redux-thunk (TS2307).

tsconfig.json:

{
  "compilerOptions": {
    "allowJs": true,
    "baseUrl": "src",
    "forceConsistentCasingInFileNames": true,
    "jsx": "react",
    "lib": [
      "es6",
      "dom",
      "es2015.promise"
    ],
    "module": "esnext",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "outDir": "build/dist",
    "rootDir": "src",
    "sourceMap": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "target": "es5",
    "skipLibCheck": true,
    "strict": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true
  },
  "exclude": [
    "build",
    "scripts",
    "acceptance-tests",
    "webpack",
    "jest",
    "src/setupTests.ts",
    "node_modules",
    "obj",
    "**/*.spec.ts"
  ],
  "include": [
    "src",
    "src/**/*.ts",
    "@types/**/*.d.ts",
    "node_modules/axios",
    "node_modules/redux-thunk"
  ]
}
JJJ
  • 32,902
  • 20
  • 89
  • 102
sef
  • 127
  • 1
  • 1
5

The vscode codebase does not use relative paths, but everything works fine for them

Really depends on your module loader. If you are using systemjs with baseurl then it would work. VSCode uses its own custom module loader (based on an old version of requirejs).

Recommendation

Use relative paths as that is what commonjs supports. If you move files around you will get a typescript compile time error (a good thing) so you will be better off than a great majority of pure js projects out there (on npm).

basarat
  • 261,912
  • 58
  • 460
  • 511
  • Loading the `vscode` codebase in Visual Studio Code itself, I get no squiggly lines, so Visual Studio Code somehow understands things like `import {notImplemented} from 'vs/base/common/errors';`, regardless of where the file that contains that code lives. How do they do it? – Daniel Perez Alvarez Jun 01 '16 at 10:50
5

I got this error, too. But with a very strange VSCode and GitHub behaviour. I renamed my files from page.ts to Page.ts and pushed the changes to the remote branch. Everything went well on my local system. But my build fails on GitHub Actions with the message, that the module Page was not found.

After some time, I recognized that the files some how were not renamed on the remote branch (but any further changes were present). I renamed them via GitHub web UI again and my build runs successful.

So checks this on the remote branch if your CI/CD build fails with TS2307.

O. Schnieders
  • 593
  • 1
  • 6
  • 16
3

Adding "baseUrl": "." will allow absolute paths (e.g. "src/components/button").

And, adding "paths" will allow starting from a specific folder. So, in your tsconfig.json file, you could add:

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

Also, after adding that configuration, you might need to restart VS Code to have it working properly.

  • Just reading through the paths code. I've not seen this key value pattern before with an @ sign etc... Is this language for the key important, does it do anything or signal anything to tsc? – Lauro235 Jan 30 '23 at 22:22
1

I faced the issue and the fix was to provide correct baseUrl and paths in compilerOptions in tsconfig.json file :-

{
...
"compilerOptions": {
    ...
    "moduleResolution": "node",
   ...
    "baseUrl": ".", // Here... try with correct values and the issue should get fixed
    "paths": {
      "*": ["src/*"] // Here... try with correct values and the issue should get fixed
    }
  }
...
}
VISHAL DAGA
  • 4,132
  • 10
  • 47
  • 53
0

If use webstorm, press Ctrl+Alt+S and bring up the settings window. Languages&Frameworks>TypeScript, enable "use tsconfig.json" option.

Feng Zhang
  • 1,698
  • 1
  • 17
  • 20
0

I had this error on updates from npm run watch and npm run hot. There were no errors the first time, or when triggering npm run dev or npm run prod.

In the end, this was a combination of webpack and ts-loader, see:

Darkproduct
  • 1,062
  • 13
  • 28
0

Sometimes the error is thrown when your class files are not properly named, e.g. I had class files named Employee instead of Employee.ts

You need to rename all your typescript files to end with either .ts or .d.ts

0

Disclaimer: Not (!) what OP asked for but probably useful to other visitors of this question:

Change your path to a relative one.

From

import x from 'src/foobar/x';

to

import x from '../foobar/x';
leonheess
  • 16,068
  • 14
  • 77
  • 112
0

i have the similar problem, and i'm using webstorm. i modified include option in tsconfig.js file as shown below:

  "include": [
    "src/**/*.tsx"
  ]

and viola, it works for me.

0

Adding, "baseUrl": ".", worked for me.

0

include the following line after compilerOptions{} in your tsconfig.json.

"exclude": ["node_modules"].

this solved the error.

desertnaut
  • 57,590
  • 26
  • 140
  • 166
0
npm install --save @types/react
desertnaut
  • 57,590
  • 26
  • 140
  • 166
EILYA
  • 358
  • 4
  • 5
  • Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? **If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient.** Can you kindly [edit] your answer to offer an explanation? – Jeremy Caney Aug 09 '23 at 01:43
0

The accepted answer didn't work for me. However, adding this option to tsconnfig.json did:

"importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */

which in turn will add the extension .js to the imported module name.

Aziz
  • 38
  • 1
  • 7
-1

removing captalize letter in the beggining of the file name worked for me, I am working on a windows machine and it worked good on local the problem was when I tryed to deploy to a linux machine.

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 06 '23 at 05:08
-4

In the Webstorm, you can create a new file instead of what you have now, copy the content from the old file to the new one, remove the old file, and then rename the new file to the old file. now you can do the import file this is work for me.