Eric. M
Eric. M

Reputation: 170

React how can i use @import

How can i use @import to import my components in my scripts from other folders in my react project.

For example i have a folder structure like this

src
|
--- App.jsx
|
--- pages
|     |___ home.jsx
|
|
--- components
      |__ HomeComponent.jsx

How can i use in home.jsx

import HomeComponent from "@components/HomeComponent"

if i just try to use import HomeComponent from "@components/HomeComponent" like this i get error module not found.

Upvotes: 1

Views: 535

Answers (2)

Santiago Siordia
Santiago Siordia

Reputation: 95

babel-plugin-module-resolver

This plugin can simplify the require/import paths in your project. For example, instead of using complex relative paths like ../../../../utils/my-utils, you can write @utils/my-utils. It will allow you to work faster since you won't need to calculate how many levels of directory you have to go up before accessing the file.

// Use this:
import MyUtilFn from 'utils/MyUtilFn';
// Instead of that:
import MyUtilFn from '../../../../utils/MyUtilFn';

// And it also work with require calls
// Use this:
const MyUtilFn = require('utils/MyUtilFn');
// Instead of that:
const MyUtilFn = require('../../../../utils/MyUtilFn');

Install the plugin

npm install --save-dev babel-plugin-module-resolver

or

yarn add --dev babel-plugin-module-resolver

Specify the plugin in your .babelrc with the custom root or alias. Here's an example:

{
  "plugins": [
    ["module-resolver", {
      "root": ["./src"],
      "alias": {
        "test": "./test",
        "underscore": "lodash"
      }
    }]
  ]
}

.babelrc.js version Specify the plugin in your .babelrc.js file with the custom root or alias. Here's an example:


const plugins = [
  [
    require.resolve('babel-plugin-module-resolver'),
    {
      root: ["./src/"],
      alias: {
        "test": "./test"
      }
    }

  ]

];

Good example: https://gist.github.com/nodkz/41e189ff22325a27fe6a5ca81df2cb91

Upvotes: 1

cEeNiKc
cEeNiKc

Reputation: 1318

You can do a relative import from pages/home.jsx like this

import HomeComponent from "../components/HomeComponent"

Here ../ means you are going up one directory level and then into components directory

You can also perform absolute imports by setting up additional tools like babel or webpack. An absolute import would look like this when you have set src as your root directory

import HomeComponent from "components/HomeComponent"

If you are using create-react-app, this setup is easy to do as all the tooling is already handled by create-react-app

You can read about it here under the absolute imports section - https://create-react-app.dev/docs/importing-a-component/

Upvotes: 3

Related Questions