tsc throws `TS2307: Cannot find module` for a local file

Typescript

Typescript Problem Overview


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...

Typescript Solutions


Solution 1 - Typescript

@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" > } > }

Solution 2 - Typescript

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"]
}

Solution 3 - Typescript

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"
  ]
}

Solution 4 - Typescript

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";

Solution 5 - Typescript

> 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).

Solution 6 - Typescript

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

Solution 7 - Typescript

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:

Solution 8 - Typescript

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

Solution 9 - Typescript

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.

Solution 10 - Typescript

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.

Solution 11 - Typescript

If using Webstorm, it just takes time to resolve. Chill out and go grab a coffee.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel Perez AlvarezView Question on Stackoverflow
Solution 1 - TypescriptDaniel Perez AlvarezView Answer on Stackoverflow
Solution 2 - TypescriptcodejockieView Answer on Stackoverflow
Solution 3 - TypescriptsefView Answer on Stackoverflow
Solution 4 - TypescriptCan ÖZGENView Answer on Stackoverflow
Solution 5 - TypescriptbasaratView Answer on Stackoverflow
Solution 6 - TypescriptFeng ZhangView Answer on Stackoverflow
Solution 7 - TypescriptDarkproductView Answer on Stackoverflow
Solution 8 - TypescriptMr ChrndahView Answer on Stackoverflow
Solution 9 - TypescriptO. SchniedersView Answer on Stackoverflow
Solution 10 - TypescriptReut LeibView Answer on Stackoverflow
Solution 11 - Typescriptuser1034912View Answer on Stackoverflow