47

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.

Dennis Vash
  • 42,190
  • 6
  • 81
  • 99
a b
  • 637
  • 1
  • 5
  • 5
  • When working with `create-react-app`, the webpack config is read from with `react-script` which really handles all the processes when using CRA. Either any attempt to run parallel webpack configs might disrupt a couple of settings or you will have to do intense configurations. Do you really need this change? How about using relative paths if you need shorter imports? – MwamiTovi Jul 24 '20 at 06:45
  • 1
    Does this answer your question? [How to avoid using relative path imports (/../../../redux/action/action1) in create-react-app](https://stackoverflow.com/questions/45213279/how-to-avoid-using-relative-path-imports-redux-action-action1-in-cre) – Emile Bergeron Jan 08 '21 at 14:36
  • @EmileBergeron this question is about **aliases** not relative/absolute paths – Dennis Vash May 10 '21 at 16:33
  • 1
    @DennisVash aliases are one of the solutions listed in that other thread, which this question is a duplicate of. – Emile Bergeron May 10 '21 at 16:49
  • In your duplicate there is only a single mention of aliases, and its related answer is a publication of the answer's library. – Dennis Vash May 20 '21 at 06:41

5 Answers5

41

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.

Igor Sukharev
  • 1,451
  • 19
  • 17
  • 6
    You always could make absolute imports via `jsconfig.json`, the question is about making *aliases* – Dennis Vash Apr 01 '21 at 09:01
  • 9
    @DennisVash the question _isn't_ about import aliases, it is about _import path shortcuts_, which this answer properly addresses. The fact that aliases are one of the multiple ways to reduce import paths length doesn't invalidate this answer. – Emile Bergeron May 10 '21 at 17:04
35

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. :)

dipenparmar12
  • 2,318
  • 1
  • 25
  • 34
  • works fine, but until `craco test` is run then it cant find the alias, do you know what can cause this? – Basit Apr 05 '22 at 23:26
34

NOTE FOR CONFUSING TERMS

// Absolute path: paths which are relative to a specific path
import Input from 'components' // src/components
import UsersUtils from 'page/users/utils' // src/page/users/utils

// Alias path: other naming to specific path
import Input from '@components' // src/components
import UsersUtils from '@userUtils' // src/page/users/utils

In order for webpack's aliases to work, you need to configure the default webpack.config.js of create-react-app.

The official way is to use the eject script.

But the recommended way is to use a library without ejecting, like craco.

After following the installation, add craco.config.js to your root folder with the desired configuration.

My example:

// craco.config.js
const path = require(`path`);
const alias = require(`./src/config/aliases`);

const SRC = `./src`;
const aliases = alias(SRC);

const resolvedAliases = Object.fromEntries(
  Object.entries(aliases).map(([key, value]) => [key, path.resolve(__dirname, value)]),
);

module.exports = {
  webpack: {
    alias: resolvedAliases,
  },
};

Where aliases.js (./src/config/aliases) exports a helper function:

const aliases = (prefix = `src`) => ({
  '@atoms': `${prefix}/components/atoms`,
  '@molecules': `${prefix}/components/molecules`,
  '@organisms': `${prefix}/components/organisms`,
  '@templates': `${prefix}/components/templates`,
  '@components': `${prefix}/components`,
  '@config': `${prefix}/config`,
  '@enums': `${prefix}/enums`,
  '@hooks': `${prefix}/hooks`,
  '@icons': `${prefix}/components/atoms/Icons`,
  '@styles': `${prefix}/styles`,
  '@utils': `${prefix}/utils`,
  '@state': `${prefix}/state`,
  '@types': `${prefix}/types`,
  '@storybookHelpers': `../.storybook/helpers`,
});

module.exports = aliases;

VSCode IntelliSense

In addition, you should add jsconfig.json file for path IntelliSense in VSCode (or tsconfig.json), see followup question.

Now such code with IntelliSense will work:

// NOTE THAT THOSE ARE ALIASES, NOT ABSOLUTE PATHS
// AutoComplete and redirection works
import {ColorBox} from '@atoms';
import {RECOIL_STATE} from '@state';
Dennis Vash
  • 42,190
  • 6
  • 81
  • 99
1

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

import { Wrapper } from 'app/components'

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

Nagibaba
  • 2,919
  • 1
  • 27
  • 34
0

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.

Abhinav Nigam
  • 355
  • 2
  • 5