TypeScript - 意外位置的node_modules

时间:2017-01-11 20:07:20

标签: typescript

如果你的node_modules不在直接树中,有没有办法让typescript导入工作?

rxjs导入类似external/node_modules的内容时,如何让Typescript不抱怨。

示例

|-- 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 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.
├─ rxjs@5.0.3
└─ symbol-observable@1.0.4
✨  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'.

1 个答案:

答案 0 :(得分:1)

您可以在tsconfig.json中使用paths mapping

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

您必须为从非标准位置导入的每个模块添加paths映射。

相关问题