如果你的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'.
答案 0 :(得分:1)
您可以在tsconfig.json中使用paths mapping:
"compilerOptions": {
....
"baseUrl": ".", // This must be specified if "paths" is.
"paths": {
"rxjs/Rx": ["external/node_modules/rxjs/Rx"]
}
}
您必须为从非标准位置导入的每个模块添加paths
映射。