我有一个 React 应用程序,我尝试使用
paths
文件中的 tsconfig.json
来简化应用程序之间的组件导入,但它只是不断抛出此错误,不知道为什么。
Failed to resolve import "@components/layout" from "src/features/filter/components/Filter.tsx". Does the file exist?
这是我的代码:
src/features/filter/components/Filter.tsx
import { Section } from "@components/layout"
src/components/layout/index.tsx
import Section from "./Section"
export {
Section,
}
src/components/layout/Section/Section.tsx
import React from "react"
type Props = {
tag: "header" | "main" | "footer" | "aside" | "article" | "section"
children?: string | React.JSX.Element | (string | React.JSX.Element)[]
}
export default function Section({ tag: Tag, children }: Props) {
return (
<Tag className="collection">
{children}
</Tag>
)
}
tsconfig.json
{
"module": "ESNext",
"moduleResolution": "bundler",
"baseUrl": "./",
"paths": {
"@features/*": ["src/features/*"],
"@components/*": ["src/components/*"]
}
}
以下是我的文件结构:
tsconfig.json
src/
├─ features/
| ├─ filter/
| ├─ components/
| ├─ Filter.tsx
├─ components/
├─ layout/
├─ index.tsx
├─ Section/
├─ Section.tsx
我知道这是打字稿的问题,因为我使用的是 CRA,它给了我错误,然后我切换到 vite,但仍然给了我同样的错误。
首先检查您是否在 vite.config.ts 中提供了路径:
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@components": path.resolve(__dirname, "./src/components"),
},
},
});
或在 tsconfig.json 中:
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"@components/*": ["components/*"]
}
}
}
布局文件夹中有多个文件和文件夹,这也可能是从“@components/layout”导入{Section}的原因;正在抛出错误。尽量具体并在最后提及文件或文件夹的名称。例如,尝试 从“@components/layout/Section/Section.tsx”导入{Section}