gon250
gon250

Reputation: 3545

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?

Upvotes: 15

Views: 16008

Answers (3)

Adam Zerner
Adam Zerner

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 or tsconfig.json file in the root of your project. If you're using TypeScript in your project, you will already have a tsconfig.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 the compilerOptions of your project's tsconfig.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

Chiamaka Ikeanyi
Chiamaka Ikeanyi

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

Vlatko Vlahek
Vlatko Vlahek

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

Related Questions