90

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.

0

5 Answers 5

76

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.

Sign up to request clarification or add additional context in comments.

4 Comments

You always could make absolute imports via jsconfig.json, the question is about making aliases
@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.
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.
Thsi wouldn't work with path alias right? typescriptlang.org/docs/handbook/modules/reference.html#paths
64

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

4 Comments

works fine, but until craco test is run then it cant find the alias, do you know what can cause this?
@craco/craco will only support till react-script v4.x.x. it doesn't supports the latest react-scripts v5.x.x
craco 7 looks like will have support for react-scripts v5.x.x, github.com/dilanx/craco/issues/454#issuecomment-1273699896
44
// 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';

1 Comment

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.
-2

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.

2 Comments

The plugin has been archived.
@VictorPudeyev You should be aware that the source GitHub repo has been archived. This means, seriously, if you have any problem in the future you have NOWHERE to report and NO ONE will fix it for you.
-3

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

4 Comments

The plugin has been archived.
nothing is archived check below link npmjs.com/package/babel-plugin-module-resolver
Yes, it's archived: github.com/tleunen/babel-plugin-module-resolver. This means it will not receive any bug-fix, resolving any possible problem a user might encounter when using it. So this is why I downvoted, not because I don't appreciate your good mind helping people. It's just because the solution itself is no longer future-proof.
So what's the alternative ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.