reactjstypescriptimport

"Failed to resolve import" using "paths" in tsconfig with React


I have a react app, and I tried to use the paths in the tsconfig.json file to simplify importing components between my application, but it just keeps throwing this error idk why.

Failed to resolve import "@components/layout" from "src/features/filter/components/Filter.tsx". Does the file exist?

Here's my code:

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/*"]
  }
}

The following is my file structure:

tsconfig.json
src/
├─ features/
|  ├─ filter/
|     ├─ components/
|        ├─ Filter.tsx
├─ components/
   ├─ layout/
      ├─ index.tsx
      ├─ Section/
         ├─ Section.tsx

I know it's a problem with typescript because I was using CRA and it was giving me the error and then I switched to vite and still is giving me the same error.


Solution

  • First check if you have provided the path in 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"),
        },
      },
    });
    

    or in tsconfig.json:

    {
      "compilerOptions": {
        "baseUrl": "src",
        "paths": {
          "@components/*": ["components/*"]
        }
      }
    }
    

    You have multiple files and folders in layout folder that could also be the reason why import { Section } from "@components/layout"; is throwing error. try to be specific and mention the name of the file or folder till the end. For example, try import { Section } from "@components/layout/Section/Section.tsx"