[英]Typescript cannot find module that was defined in "paths" setting
在我的 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-loader
與 Webpack 2 一起使用,我還在其中包含了用於加載路徑的插件。 我也使用 Visual Studio Code,它內置了 Typescript,但顯示相同的錯誤。
在我的 Typescript 組件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'
添加import { Test } from 'app/components'
Typescript會查看src/app/components/index.js
並且它可以工作。 我還想將@
添加到別名以避免與其他模塊沖突。 像這樣:
"@app*": ["src/app*"]
對於像這樣的文件夾結構:
[rootDir]
|
|- [src]
| |
| |-[app]
| |
| |-[components]
| | ... react components live here
| |- Test.tsx
像這樣導入:
import { Test } from 'app/components'
您需要在tsconfig.json
中的"src/components/*
"src/components"
:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"app*": ["src/components", "src/components/*"]
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.