DEV Community

Emmanuel Ifeanyi MECHIE
Emmanuel Ifeanyi MECHIE

Posted on

How to use absolute path in ReactJs

Absolute Path vs Relative Path?
Absolute Path is when you source for a folder or file from the root either where your system storage start from or where the project start from.
Absolute Path
Relative Path is when you try to source for a file or folder taken into consideration where you are currently located in the project structure.
Relative Path

Steps to configure your React project with absolute path.

  1. Create React App
  2. Add jsconfig.json
  3. Import file with absolute path

Create React App

if you already have react app to configure you can skip this step

npx create-react-app app_name
Enter fullscreen mode Exit fullscreen mode

App.js

import Button from "./components/button";

const App = () => {
  return (
    <div>
      <Button />
      <Card></Card>
    </div>
  );
};

export default App;

Enter fullscreen mode Exit fullscreen mode

Add jsconfig.json

in your project add jsconfig.json beside package.json
Project Structure

jsconfig.js

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "exclude": ["node_modules", "build"],
  "include": ["src"]
}

Enter fullscreen mode Exit fullscreen mode

for typescript create tsconfig.json

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}
Enter fullscreen mode Exit fullscreen mode

Import with absolute path

import Button from "components/button";

const App = () => {
  return (
    <div>
      <Button />
      <Card></Card>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

Collapse
favouritejome profile image
Favourite Jome

Hi, is there a reason to do this?