78

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
  • 50,196
  • 9
  • 100
  • 118
a b
  • 947
  • 1
  • 6
  • 7
  • 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
  • 1
    @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
  • I have tried it with my babel module parser. it worked in the run. But facing a module import issue in build. can anyone help me ? – Shahnad S Jan 20 '23 at 09:30

5 Answers5

69

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
  • 2,467
  • 24
  • 21
  • 14
    You always could make absolute imports via `jsconfig.json`, the question is about making *aliases* – Dennis Vash Apr 01 '21 at 09:01
  • 13
    @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
  • 2
    Works but I think it's flawed. It could conflict with package names and does not make it clear that the imports are relative to the src folder in the sourcecode. – Janis Jansen Jun 24 '22 at 08:25
51

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

yurylavrukhin
  • 42
  • 1
  • 6
dipenparmar12
  • 3,042
  • 1
  • 29
  • 39
  • 1
    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
  • 1
    @Basit refer to https://github.com/dilanx/craco/blob/master/recipes/add-webpack-alias-to-jest/craco.config.js – Abe Caymo Sep 28 '22 at 10:17
  • @craco/craco will only support till react-script v4.x.x. it doesn't supports the latest react-scripts v5.x.x – Viraj Singh Oct 22 '22 at 06:35
  • 1
    craco 7 looks like will have support for react-scripts v5.x.x, https://github.com/dilanx/craco/issues/454#issuecomment-1273699896 – giankotarola Oct 28 '22 at 23:53
45
// 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 (find the most modern library for that).

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';
dipenparmar12
  • 3,042
  • 1
  • 29
  • 39
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
  • Does this still apply today? I tried putting Game.js in `src/components`, then using `import Game from 'components/Game'; - it didn't work. Gave me the error saying `Requests that should resolve in the current directory need to start with './'. Requests that start with a name are treated as module requests and resolve within module directories...` - perhaps this behaviour has changed. – Jez Aug 30 '22 at 00:45
  • Just a note of caution, craco is now basically abandonded and stuck on an old version of create-react-app. I would advice against using it. I would also add this to the above answer as this is not a good idea if you are just starting a new project. https://github.com/dilanx/craco/issues/378#issuecomment-1108663751 – sethreidnz Sep 29 '22 at 23:27
  • Update craco has been updated finally and my above message is not true anymore! – sethreidnz Apr 28 '23 at 08:06
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
  • 503
  • 4
  • 5
0

Step 1

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

add this plugin

Step 2

in babel.config.js file

ALIAS NAME    ALIAS PATH

@navigation   ./src/navigation
@components   ./src/components
@assets       ./assets

[
  "module-resolver",
  {
    root: ["./src"],
    alias: {
      "^~(.+)": "./src/\\1",
    },
    extensions: [
      ".ios.js",
      ".android.js",
      ".js",
      ".jsx",
      ".json",
      ".tsx",
      ".ts",
      ".native.js",
    ],
  },
];

Step 3

import example

import SomeComponent from '@components/SomeComponent.js';

Step 4 restart server

yarn start

Reference link: How to use import aliases with React native and VSCode

David Buck
  • 3,752
  • 35
  • 31
  • 35
Madhav
  • 317
  • 2
  • 12