小编典典

打字稿找不到在“路径”设置中定义的模块

reactjs

在我的React项目中,我在webpack配置中定义了一个模块别名。我想开始移至Typescript。

//我尽力简化设置

这是我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-loaderWebpack 2与一起使用,并且在其中也包含了用于加载路径的插件。我也使用Visual
Studio Code,它内置了Typescript,但是显示了相同的错误。

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

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

我收到以下错误:

Cannot find module 'app/components'

阅读 429

收藏
2020-07-22

共1个答案

小编典典

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

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

现在,当我添加import { Test } from 'app/components'Typescript时,它将开始研究src/app/components/index.js并起作用。我还喜欢添加@别名以避免与其他模块发生冲突。像这样:

  "@app*": ["src/app*"]
2020-07-22