0

Is there any way to get typescript imports working if your node_modules are not located in direct tree?

How can I make Typescript not complain when importing something like rxjs from external/node_modules.

Example:

tree

|-- external
|  `-- package.json
|-- index.ts
`-- tsconfig.json

cat tsconfig.json

{
    "compilerOptions": {
        "module": "amd",
        "target": "es5",
        "sourceMap": true,
        "removeComments": true,
        "allowJs": false,
        "pretty": true,
        "experimentalDecorators": true,
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "lib": [ "es2015", "dom" ]
    }
}

cat external/package.json

{
    "name": "external",
    "version": "1.0.0",
    "main": "index.js",
    "license": "MIT",
    "dependencies": {
        "rxjs": "^5.0.3"
    }
}

cat index.ts

import { Observable } from 'rxjs/Rx';
Observable

cd external

yarn install

yarn add v0.18.1
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 📃  Building fresh packages...
success Saved lockfile.
success Saved 2 new dependencies.
├─ [email protected]
└─ [email protected]
✨  Done in 1.39s.

tsc -v

Version 2.1.4

tsc

1 import { Observable } from 'rxjs/Rx';
                             ~~~~~~~~~

../index.ts(1,28): error TS2307: Cannot find module 'rxjs/Rx'.
0

1 Answer 1

1

You can use paths mapping in tsconfig.json:

  "compilerOptions": {
    ....
    "baseUrl": ".", // This must be specified if "paths" is.
    "paths": {
      "rxjs/Rx": ["external/node_modules/rxjs/Rx"]
    }
  }

You have to add paths mapping for every module you import from non-standard location.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah well, that makes sense! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.