【发布时间】:2019-01-29 18:09:13
【问题描述】:
我的项目结构如下:
<PROJECT_FOLDER>
├── node_modules
├── src
│ ├── components
│ │ └── MyAwesomeComponent.tsx
│ ├── views
│ │ └── MyAwesomeView
│ │ └── index.tsx
│ ├── Application.tsx
│ └── index.tsx
├── webpack.config.js
└── tsconfig.json
还有以下tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"moduleResolution": "classic",
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true,
"sourceMap": true,
"noImplicitReturns": true,
"experimentalDecorators": true,
"baseUrl": ".",
"paths": {
"*": [
"src/*",
"node_modules/*"
]
},
}
}
假设我在node_modules 中有react(甚至安装了@types/react)。当我尝试导入一些东西时,例如import * as React from "react" 或import MyComponent from "components/MyAwesomeComponent,两个导入都是错误的,消息 “找不到模块...” 等等。
在我编写导入字符串时,VSCode 建议我使用来自 node_modules 的模块,但不建议我使用来自 src/* 的文件夹。
相对导入仍然有效,但这是地狱,你知道的。
我绝对是 TypeScript 的新手,但我正在根据“模块解析”TypeScript 文档做事,但它不起作用。
非常感谢这里的任何帮助!
更新
我已将我的moduleResolution 更改为node 并设置@Alserda 共享的配置(感谢您的回答,但看起来我做错了,因为您的配置不能解决问题)。然后我运行建议的tsc --traceResolution。它也解决了我的所有导入问题,VSCode 现在解决了node_modules,但仍然无法解决我的components/MyAwesomeComponent:
更新 2
嗯,我的webpack.config.js 确实已经有了相应的模块
但我不认为问题出在这里,我什至没有运行webpack-dev-server,而且我相信VSCode没有使用webpack.config.js信息来配置项目:)
更新 3
这是 components/MyAwesomeComponent 导入的输出:
======== Resolving module 'components/MyAwesomeComponent' from '/home/username/path/to/project/src/Application.tsx'. ========
Explicitly specified module resolution kind: 'NodeJs'.
'baseUrl' option is set to '/home/username/path/to/project/src', using this value to resolve non-relative module name 'components/MyAwesomeComponent'.
Resolving module name 'components/MyAwesomeComponent' relative to base url '/home/username/path/to/project/src' - '/home/username/path/to/project/src/components/MyAwesomeComponent'.
Loading module as file / folder, candidate module location '/home/username/path/to/project/src/components/MyAwesomeComponent', target file type 'TypeScript'.
File '/home/username/path/to/project/src/components/MyAwesomeComponent.ts' does not exist.
File '/home/username/path/to/project/src/components/MyAwesomeComponent.tsx' exist - use it as a name resolution result.
======== Module name 'components/MyAwesomeComponent' was successfully resolved to '/home/username/path/to/project/src/components/MyAwesomeComponent.tsx'. ========
最终更新
即使在Reload TypeScript project 之后,VSCode 也没有强制从我的tsconfig.json 更新项目设置。我刚刚重新启动它,现在一切正常! :)
感谢大家的帮助!
【问题讨论】:
-
尝试
tsc和--traceResolution以获取有关正在发生的事情的更多信息。 -
@MattMcCutchen 我已经更新了我的答案
-
您能否在
--traceResolution输出中搜索components/MyAwesomeComponent并将相关输出添加到问题中,以便我们了解解决方案是如何失败的? -
对不起,我没有仔细阅读这个问题。 VSCode 应该使用你的 tsconfig.json;我对差异没有任何想法,不幸的是我也没有任何进一步调试的想法,除了重新启动 VSCode,如果你还没有这样做的话。
-
"我刚刚重新启动它,现在一切正常!"
标签: reactjs typescript webpack visual-studio-code