Imports not picking absolute path other than immediate sub folder to baseUrl path (src) #9229
Unanswered
krajasekhar
asked this question in
Q&A
Replies: 1 comment
-
Absolute Path Imports in Create React AppYou can absolutely use absolute imports from Method 1: jsconfig.json (Easiest - JavaScript)Create {
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}Now import from // Before (relative)
import Button from "../../../../../components/Button";
// After (absolute)
import Button from "components/Button";
import { useAuth } from "hooks/useAuth";
import { API_URL } from "constants/config";Method 2: tsconfig.json (TypeScript)For TypeScript projects, add to {
"compilerOptions": {
"baseUrl": "src",
"paths": {
"@components/*": ["components/*"],
"@hooks/*": ["hooks/*"],
"@utils/*": ["utils/*"],
"@/*": ["./*"]
}
}
}Usage: import Button from "@components/Button";
import { useAuth } from "@hooks/useAuth";
import { API_URL } from "@constants/config";Why Nested Folders Fail (Your Issue)// ❌ Won't work - only baseUrl, not sub-folders
import something from "components/Button/nested";
// ✅ Must use full path from src
import something from "components/Button/nested/file";The
Recommended StructureOrganize like this for best results: Then import anywhere: // In any file, at any depth
import Button from "components/Button";
import { useAuth } from "hooks/useAuth";IDE SupportVS Code + Pylance automatically recognize
Common Gotchas
Current Directory Issue// ❌ This fails
import X from "pages/Dashboard/AnotherFile";
// ✅ This works - explicit full path
import X from "pages/Dashboard/AnotherFile";
// ✅ Or use relative for same directory
import X from "./AnotherFile";That's it! Add See: https://create-react-app.dev/docs/importing-a-component/ |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
To have imports from absolute path, I am configuring baseUrl and paths in
jsconfig.jsonand facing below issues.My app folder structure:
When I configure
jsconfig.jsonlike this1.
it is failing at
import {someThing} from 'assets/someFile'with errorModule not found: Can't resolve 'assets/someFile'. No error forcomponents/viewsfolders imports.2.
it is failing at
import {someThing} from 'views/someFile'with errorModule not found: Can't resolve 'views/someFile'. No error forassetsfolders imports.but vs code is navigating to the source file when I do 'Ctrl + click' on the path with any of above config.
Beta Was this translation helpful? Give feedback.
All reactions