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
Typescript cannot find module that was defined in "paths" setting
提问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.json
in 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-loader
with 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-loader
Webpack 2 并且我还在那里包含了插件来加载路径。我也使用 Visual Studio Code,它内置了 Typescript,但显示了相同的错误。
In my Typescript component SomeComponent.tsx
I 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.js
and 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*"]