'How to make an import shortcut/alias in create-react-app?

How to set import shortcuts/aliases in create-react-app? From this:

import { Layout } from '../../Components/Layout'

to this:

import { Layout } from '@Components/Layout'

I have a webpack 4.42.0 version. I don't have a webpack.config.js file in the root directory. I've tried to create one myself with this code inside:

const path = require('path')

module.exports = {
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src/'),
    }
  }
};

But it doesn't seem to work. I've seen the NODE_PATH=. variant in .env file. But I believe, it is deprecated - better not to use. And also, I have a posstcss.config.js file. Because I've installed the TailwindCss and I import the CSS library there. I've tried to paste the same code there, but it also didn't work.



Solution 1:[1]

It is finally possible with Create React App v.3

Just put:

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

into jsconfig.json or tsconfig.json if you use Typescript

Here is wonderful article about this.

Solution 2:[2]

Simplest way to archive this follow below steps. (same way as @DennisVash showed as but in simple form)

  1. Installation - install and setup CRACO.
yarn add @craco/craco

# OR

npm install @craco/craco --save
  1. Create a craco.config.js file in the root directory and configure CRACO:
/* craco.config.js */
const path = require(`path`);

module.exports = {
  webpack: {
    alias: {
      '@': path.resolve(__dirname, 'src/'),
      '@Components': path.resolve(__dirname, 'src/components'),
      '@So_on': path.resolve(__dirname, 'src/so_on'),
    }
  },
};
  1. Update the existing calls to react-scripts in the scripts section of your package.json file to use the craco CLI:
/* package.json */

"scripts": {
   "start": "craco start",
   "build": "craco build",
   "test": "craco test"
}

Done! Setup is completed.

Now let's test it.

// Before
import Button from "./form/Button" 
import { Layout } from '../../Components/Layout'

// After
import Button from "@/form/Button"
import { Layout } from '@Components/Layout'

Documentation Craco

Thank you. :)

Solution 3:[3]

React already has built-in import shortcut starting from /src folder.

import { Wrapper } from 'app/components'

PS: is created by "baseUrl": "./src"

Solution 4:[4]

If you want to use:

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

use the node module plugin for resolving the urls https://www.npmjs.com/package/babel-plugin-module-resolver. By installing it and adding it to your webpack/babel.rc file.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Igor Sukharev
Solution 2 yurylavrukhin
Solution 3 Nagibaba
Solution 4 Abhinav Nigam