Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add absolute paths to app created by "Create React App"

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?

like image 958
gon250 Avatar asked Mar 18 '19 10:03

gon250


People also ask

How do you create an absolute path in react?

When initializing React Project with create-react-app, we can configure our React application to support importing modules with absolute paths. Note: We can create the jsconfig. json file if it doesn't exist. Now we have the working absolute imports setting with src folder as custom base directory.

How do I add absolute imports in react?

According to create-react-app Docs, We can use absolute imports in our react project by configuring a jsconfig. json / tsconfig. json (for typescript projects) file in the root of our project. If you're using TypeScript in your project, you will already have a tsconfig.

Can I use npm With create react app?

Create React App is a comfortable environment for learning React, and is the best way to start building a new single-page application in React. npx on the first line is not a typo — it's a package runner tool that comes with npm 5.2+.


2 Answers

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';
like image 158
Chiamaka Ikeanyi Avatar answered Sep 22 '22 01:09

Chiamaka Ikeanyi


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.

like image 25
Vlatko Vlahek Avatar answered Sep 24 '22 01:09

Vlatko Vlahek