VS Code React项目jsconfig路径别名配置优化及深层路径写法问询
Q&A: JSConfig Path Aliases for React in VS Code
Let's break down your questions clearly, with practical solutions tailored to your VS Code setup:
1. Can we merge the two @Loader path configurations into a single line?
Good news—you don’t actually need two separate lines! The confusion here stems from how path aliases work in jsconfig.json:
If you only define this single alias:
"@Loader": ["./src/components/Loader"]
It will handle both of your import scenarios seamlessly:
import BlablaDefault from "@Loader": Resolves to./src/components/Loader/index.js(or the entry file specified in the directory’spackage.json, if you have one)import Blabla from "@Loader/blabla": Automatically maps to./src/components/Loader/blabla.js(orblabla/index.jsif it’s a subdirectory)
The separate @Loader/* rule you added is redundant here. The base @Loader alias inherently supports all nested imports under that directory.
If you insist on keeping both patterns (even though it’s unnecessary), you can’t merge them into one key-value pair—they match distinct import patterns (root module vs. subpaths). But you could format them on the same line for brevity (though this harms readability):
"@Loader": ["./src/components/Loader"], "@Loader/*": ["./src/components/Loader/*"]
Again, the single-line @Loader alias is the cleaner, more efficient solution.
2. Glob pattern for deeply nested components like @DeepStuff/blabla1/blabla2/blabla3
You don’t need any fancy glob syntax here—standard path alias rules handle deep nesting automatically.
Suppose your DeepStuff directory lives at ./src/components/DeepStuff. Just add this single alias:
"@DeepStuff": ["./src/components/DeepStuff"]
This will resolve:
import Deep from "@DeepStuff/blabla1/blabla2/blabla3"→./src/components/DeepStuff/blabla1/blabla2/blabla3.js(or the corresponding directory entry file)
If you prefer the /* syntax (again, redundant but functional), you could write:
"@DeepStuff/*": ["./src/components/DeepStuff/*"]
The * wildcard matches any sequence of characters, including multiple path segments separated by /.
Optimized jsconfig.json Example
Here’s how your full config would look with the streamlined aliases:
{ "compilerOptions": { "module": "commonjs", "target": "es2019", "jsx": "react", "baseUrl": ".", "paths": { "@Reducers/*": ["./src/reducers/*"], "@Selectors/*": ["./src/selectors/*"], "@Components/*": ["./src/components/*"], "@App/*": ["./src/components/App/*"], "@Loader": ["./src/components/Loader"], "@DeepStuff": ["./src/components/DeepStuff"] } }, "include": ["src/**/*"], "exclude": ["node_modules", "dist", "config", ".vscode"] }
内容的提问来源于stack exchange,提问作者Javier Guzmán

