Clem
Clem

Reputation: 11824

TypeScript - node_modules in unexpected location

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

Upvotes: 0

Views: 884

Answers (1)

artem
artem

Reputation: 51629

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.

Upvotes: 1

Related Questions