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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44463100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:37:27  来源:igfitidea点击:

Typescript cannot find module that was defined in "paths" setting

javascriptreactjstypescript

提问by Chris

In my React project I have a module alias defined in webpack config. I want to start moving over to Typescript.

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

// I tried to simplify the setup as much as it makes sense

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

This is my tsconfig.jsonin the root folder:

这是我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/**/*"
  ]
}

This is my project structure:

这是我的项目结构:

[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

I use the awesome-typescript-loaderwith Webpack 2 and I also included the plugin there to load the paths. I also use Visual Studio Code and it has Typescript built in, but that shows the same error.

我使用awesome-typescript-loaderWebpack 2 并且我还在那里包含了插件来加载路径。我也使用 Visual Studio Code,它内置了 Typescript,但显示了相同的错误。

In my Typescript component SomeComponent.tsxI want to include another component like so:

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

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

I get the following error:

我收到以下错误:

Cannot find module 'app/components'

回答by Chris

The solution is to edit the paths config to find nested files.

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

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

Now when I add import { Test } from 'app/components'Typescript will look into src/app/components/index.jsand it works. I also like to add @to aliases to avoid conflicts with other modules. Like so:

现在,当我添加import { Test } from 'app/components'Typescript 时src/app/components/index.js,它会查看它的工作原理。我还喜欢添加@别名以避免与其他模块发生冲突。像这样:

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