【问题标题】:TypeScript - node_modules in unexpected locationTypeScript - node_modules 在意外位置
【发布时间】:2017-01-11 20:07:19
【问题描述】:

如果你的 node_modules 不在直接树中,有什么方法可以让 typescript 导入工作?

external/node_modules 导入rxjs 之类的内容时,如何让Typescript 不报错。

示例

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

猫 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 外部/package.json

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

猫索引.ts

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

cd 外部

纱线安装

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

【问题讨论】:

    标签: typescript


    【解决方案1】:

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

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

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

    【讨论】:

    • 嗯,有道理!谢谢!
    猜你喜欢
    • 2015-06-21
    • 2015-11-20
    • 2018-01-29
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2017-12-17
    • 1970-01-01
    相关资源
    最近更新 更多