How to make an import shortcut/alias in create-react-app?
Asked Answered
S

5

85

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.

Seem answered 24/7, 2020 at 5:46 Comment(0)
K
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';
Keon answered 24/7, 2020 at 7:6 Comment(1)
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.Stalnaker
R
75

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.

Rufinaruford answered 19/1, 2021 at 11:40 Comment(3)
You always could make absolute imports via jsconfig.json, the question is about making aliasesKeon
@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.Tumulus
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.Intern
F
58

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

Flossieflossy answered 16/1, 2021 at 5:33 Comment(4)
works fine, but until craco test is run then it cant find the alias, do you know what can cause this?Vacua
@Vacua refer to github.com/dilanx/craco/blob/master/recipes/…Aircool
@craco/craco will only support till react-script v4.x.x. it doesn't supports the latest react-scripts v5.x.xPersonality
craco 7 looks like will have support for react-scripts v5.x.x, github.com/dilanx/craco/issues/454#issuecomment-1273699896Sixgun
K
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';
Keon answered 24/7, 2020 at 7:6 Comment(1)
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.Stalnaker
X
-1

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.

Xanthochroism answered 1/4, 2021 at 8:30 Comment(2)
The plugin has been archived.Sedimentation
@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.Sedimentation
C
-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

Client answered 5/1, 2023 at 4:50 Comment(4)
The plugin has been archived.Sedimentation
nothing is archived check below link npmjs.com/package/babel-plugin-module-resolverClient
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.Sedimentation
So what's the alternative ?Client

© 2022 - 2024 — McMap. All rights reserved.