I am creating a react-app using the create-react-app tool so it uses webpack for module bundling. Having the following directory structure
-my-app
--node_modules
--src
---components
----somecomponent
-----SomeComponent.jsx
----someothercomponent
-----SomeOtherComponent.jsx
----main.js
----public
To avoid many ../../
(dot dot slashes for the relative path) I have set a NODE_PATH=./src
as shown below in my package.json
"scripts": {
"start": "NODE_PATH=./src react-scripts start",
"build": "NODE_PATH=./src react-scripts build",
}
So I can now import my modules in my like this
import SomeComponent from "/components/somecomponent/SomeComponent"
So even changing the directory structure will not break my code as often. But with this my VSCode doensn't recognise paths and thus doesn't show the intellisense, how do I fix it?
I work on JS and TS support for VSCode. For this use case, I think you have a few options:
Create a jsconfig.json
in the root of your project and use baseUrl
:
{
"compilerOptions": {
"baseUrl": "./src"
}
}
This should allow for imports such as:
import SomeComponent from "components/somecomponent/SomeComponent"
Alternately, use the paths
property:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"~/*": ["./src/*"]
}
}
}
this would allow imports of the form:
import SomeComponent from "~/components/somecomponent/SomeComponent"
You can find more details about these configuration options here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With