Reputation: 3545
I have created an app by Create React App and to be more specific I'm also using typescript.
I can't figerout how to set absolute paths to access to my components, pages, etc..
In a different scenario I would update my tscongig with something like:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@components/*": ["src/components/*"]
}
}
}
but I have no idea how to implement this as I'm using react-scripts
any idea?
Upvotes: 15
Views: 16008
Reputation: 19278
See Building Your App / Importing a Component / Absolute Imports in the Create React App docs.
You can configure your application to support importing modules using absolute paths. This can be done by configuring a
jsconfig.json
ortsconfig.json
file in the root of your project. If you're using TypeScript in your project, you will already have atsconfig.json
file.Below is an example
jsconfig.json
file for a JavaScript project. You can create the file if it doesn't already exist:{ "compilerOptions": { "baseUrl": "src" }, "include": ["src"] }
If you're using TypeScript, you can configure the
baseUrl
setting inside thecompilerOptions
of your project'stsconfig.json
file.Now that you've configured your project to support absolute imports, if you want to import a module located at
src/components/Button.js
, you can import the module like so:import Button from 'components/Button';
Upvotes: 1
Reputation: 484
Create a tsconfig.json file and add the code below.
{
"compilerOptions": {
"baseUrl": "src"
},
"include": [
"src"
]
}
Then you can import your components as
import Header from 'components/Header';
Upvotes: 14
Reputation: 1889
You should be able to use the same approach if create a jsconfig.json file in your solution, which supports the same baseUrl and rootPath properties as tsconfig.
Alternative is adding an .env file in your solution with the following line:
NODE_PATH=src/
Also, apart from the env file add this to your jsconfig.json
{
"rootDir": "src",
"compilerOptions": {
"baseUrl": "src",
"paths": {
"*": ["*"]
}
}
}
This should resolve both the compiler being able to find your absolute imports, and linter handling them properly.
Upvotes: 7