在我的React项目中,我在webpack配置中定义了一个模块别名。我想开始移至Typescript。
//我尽力简化设置
这是我tsconfig.json在根文件夹中:
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,但是显示了相同的错误。
awesome-typescript-loader
在我的Typescript组件中,SomeComponent.tsx我想包含另一个组件,如下所示:
SomeComponent.tsx
import * as React from 'react' import { Test } from 'app/components'
我收到以下错误:
Cannot find module 'app/components'
解决方案是编辑路径配置以查找嵌套文件。
"baseUrl": ".", "paths": { "app*": ["src/app*"] }
现在,当我添加import { Test } from 'app/components'Typescript时,它将开始研究src/app/components/index.js并起作用。我还喜欢添加@别名以避免与其他模块发生冲突。像这样:
import { Test } from 'app/components'
src/app/components/index.js
@
"@app*": ["src/app*"]