Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript cannot find module that was defined in "paths" setting

Tags:

In my React project I have a module alias defined in webpack config. I want to start moving over to Typescript.

// I tried to simplify the setup as much as it makes sense

This is my tsconfig.json in the root folder:

{   "compilerOptions": {     "target": "es6",     "module": "es6",     "moduleResolution": "node",     "jsx": "react",     "noImplicitAny": true,     "strictNullChecks": true,     "sourceMap": true,     "lib": [       "dom",       "es2015",       "es2016"     ],     "baseUrl": "./src",     "paths": {       "app": ["./app"]     }   },   "include": [     "src/**/*"   ] } 

This is my project structure:

[rootDir] | |- [src] |  | |  |-[app] |    | |    |-[components] |      | ... react components live here |      |- Test.tsx |      |- SomeComponent.tsx |      |- index.js (export { default as Test } from './Test') | |- tsconfig.json |- webpack.config.js 

I use the awesome-typescript-loader with Webpack 2 and I also included the plugin there to load the paths. I also use Visual Studio Code and it has Typescript built in, but that shows the same error.

In my Typescript component SomeComponent.tsx I want to include another component like so:

import * as React from 'react' import { Test } from 'app/components' 

I get the following error:

Cannot find module 'app/components' 
like image 859
Chris Avatar asked Jun 09 '17 16:06

Chris


People also ask

Can not find module path?

To solve the "Cannot find module path or its corresponding type declarations" error, install the types for node by running the command npm i -D @types/node . You can then import path with the following line of code import * as path from 'path' .

Can not find module TS?

The "Cannot find module or its corresponding type declarations" error occurs when TypeScript cannot locate a third-party or local module in our project. To solve the error, make sure to install the module and try setting moduleResolution to node in your tsconfig. json file.

What is moduleResolution?

Module resolution is the process the compiler uses to figure out what an import refers to. Consider an import statement like import { a } from "moduleA" ; in order to check any use of a , the compiler needs to know exactly what it represents, and will need to check its definition moduleA .


1 Answers

The solution is to edit the paths config to find nested files.

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

Now when I add import { Test } from 'app/components' Typescript will look into src/app/components/index.js and it works. I also like to add @ to aliases to avoid conflicts with other modules. Like so:

  "@app*": ["src/app*"] 
like image 88
Chris Avatar answered Sep 23 '22 04:09

Chris