Relative Imports in React.js

Viewed 715

Currently I have an import which looks like this

import Button from "../../../components/Button/Button"

but I want to make it relative so I wouldn't require to type the ../../../ time and again.

I want to import using this method:

import Button from "components/Button/Button" or src/components/Button/Button

but please also assure that it will work on both production and development.

3 Answers

If you are using vscode with project created with create-react-app you can try adding a jsconfig.json file in root with this .

{
 "compilerOptions": {
  "baseUrl": "src"
  },
 "include": ["src"]
 }

If you are using webpack. You can use resolve.

const path = require('path');

module.exports = {
  //...
  resolve: {
    alias: {
      Utilities: path.resolve(__dirname, 'src/utilities/'),
      Templates: path.resolve(__dirname, 'src/templates/'),
      Components: path.resolve(__dirname, 'src/components/'),
    }
  }
};

Now, instead of using relative paths when importing like so:

import Utility from '../../utilities/utility';
import Button from '../../src/components/Button';

you can use the alias:

import Utility from 'Utilities/utility';
import Button from 'Components/Button';

you can download the react snippet plugig to help you with import

import Butoon from './component/Button/Button' I Think

Related