Typescript找不到"路径"中定义的模块。设置

时间:2017-06-09 16:52:20

标签: javascript reactjs typescript

在我的React项目中,我在webpack config中定义了一个模块别名。我想开始转向打字稿。

//我试图尽可能地简化设置

这是根文件夹中的tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "es6",
    "moduleResolution": "node",
    "jsx": "react",
    "noImplicitAny": true,
    "strictNullChecks": true,
    "sourceMap": true,
    "lib": [
      "dom",
      "es2015",
      "es2016"
    ],
    "baseUrl": "./src",
    "paths": {
      "app": ["./app"]
    }
  },
  "include": [
    "src/**/*"
  ]
}

这是我的项目结构:

[rootDir]
|
|- [src]
|  |
|  |-[app]
|    |
|    |-[components]
|      | ... react components live here
|      |- Test.tsx
|      |- SomeComponent.tsx
|      |- index.js (export { default as Test } from './Test')
|
|- tsconfig.json
|- webpack.config.js

我将awesome-typescript-loader与Webpack 2一起使用,我还在其中包含插件来加载路径。我也使用Visual Studio Code,它内置了Typescript,但显示相同的错误。

在我的Typescript组件SomeComponent.tsx中,我希望包含另一个组件,如下所示:

import * as React from 'react'
import { Test } from 'app/components'

我收到以下错误:

Cannot find module 'app/components'

1 个答案:

答案 0 :(得分:6)

解决方案是编辑路径配置以查找嵌套文件。

"baseUrl": ".",
"paths": {
  "app*": ["src/app*"]
}

现在当我添加import { Test } from 'app/components'时,Typescript会查看src/app/components/index.js并且它有效。我还想将@添加到别名以避免与其他模块冲突。像这样:

  "@app*": ["src/app*"]