How to avoid using relative path imports (/../../../redux/action/action1) in create-react-app

55,955

Solution 1

Create a file called .env in the project root and write there:

NODE_PATH=src

Then restart the development server. You should be able to import anything inside src without relative paths.

Note I would not recommend calling your folder src/redux because now it is confusing whether redux import refers to your app or the library. Instead you can call your folder src/app and import things from app/....

We intentionally don't support custom syntax like @redux because it's not compatible with Node resolution algorithm.

Solution 2

The approach in the accepted answer has now been superseded. Create React App now has a different way to set absolute paths as documented here.

To summarise, you can configure your application to support importing modules using absolute paths by doing the following:

Create/Edit your jsconfig.json/tsconfig.json in the root of your project with the following:

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

Once you have done this you can then import by specifying subdirectories of "src" (in the following example, components is a subdirectory of src) e.g.

import Button from 'components/Button'

Solution 3

After you try Ben Smith's solution above if you find eslint complains about importing absolute path add the following line to your eslint config:

settings: {
  'import/resolver': {
    node: {
      paths: ['src'],
    },
  },
},

replace 'src' with your folder if you use your own boilerplate with your folder's name.

Solution 4

We can use webpack 2 resolve property in the webpack config.

Sample webpack config using resolve :

Here component and utils are independent folder containing React components.

resolve: {
        modules: ['src/scripts', 'node_modules'],
        extensions: ['.jsx', '.js'],
        unsafeCache: true,
        alias: {
            components: path.resolve(__dirname, 'src', 'scripts', 'components'),
            utils: path.resolve(__dirname, 'src', 'scripts', 'utils'),
        }
    }

After that we can import directly in files :

import UiUtils from 'utils/UiUtils';
import TabContent from 'components/TabContent';

Webpack 2 Resolve Reference

Solution 5

Feb 2010
Wasted about an hour on this. An example is below:

Goal: Import App.css in HomePage.js

myapp\src\App.css
myapp\src\pages\HomePage.js

File: jsconfig.json

{
  "compilerOptions": {
    "baseUrl": "src"
  }
}

File: src\pages\HomePage.js

import "App.css";
Share:
55,955
Prem
Author by

Prem

I'm a passionate developer mainly focusing on web applications and have a hands on experience on frontend with reactjs, angularjs etc. On Backend i do have experience in Nodejs, PHP, Python and usually used to deploy them on AWS or GCP. Although an AWS fanboy i do work with GCP sometimes. I do make useful youtube videos on web development don't forget to visit my channel https://youtube.com/dcoders

Updated on January 05, 2022

Comments

  • Prem
    Prem over 2 years

    I've been using create-react-app package for creating a react website. I was using relative paths throughout my app for importing components, resources, redux etc. eg, import action from '../../../redux/action

    I have tried using module-alis npm package but with no success. Is there any plugin that I can use to import based on the folder name or alias i.e. an absolute path?

    Eg., import action from '@redux/action' or import action from '@resource/css/style.css'

  • Prem
    Prem almost 7 years
    I use create-react-app package where i cannot modify the webpack config. Is there any other way of doing it?
  • santosh
    santosh almost 7 years
    webpack.config.js is available in below path : /create-react-app/blob/master/packages/react-scripts/config/‌​webpack.config.dev.j‌​s /create-react-app/blob/master/packages/react-scripts/config/‌​webpack.config.prod.‌​js
  • Dan Abramov
    Dan Abramov almost 7 years
    This won't work with Create React App. It does not support custom Babel plugins.
  • Dan Abramov
    Dan Abramov almost 7 years
    No, it is not supported to modify these configs. You can eject but then you lose many benefits of CRA. Please see my answer for a supported way of doing this.
  • yerassyl
    yerassyl over 6 years
    Can I do this in react-create-app? I tried, but it seem not to work, although guy from here medium.com/@ktruong008/… suggest the same
  • qwang07
    qwang07 over 6 years
    @Mehari what's your version of create-react-app and react-scripts?
  • mehari
    mehari over 6 years
    @qwang create-react-app-1.4.3 & react-scripts-1.0.14
  • Prem
    Prem about 6 years
    More details about implementation can be found here - youtu.be/xHiCRpfZIO8
  • jwanglof
    jwanglof almost 6 years
    This works for us locally but not when we're building in Jenkins (we have a React-app within a Node-app), anyway, we got around this problem to add this to React's package.json instead: {"scripts": {"build": "NODE_PATH=./src react-scripts build"}} Now the build works in our Jenkins setup as well. Thanks for the tip!
  • jwanglof
    jwanglof almost 6 years
    This gave me a lead how to fix our "react-scripts build". See my comment in @dan-abramov 's answer (stackoverflow.com/a/45214138/2986873). Thanks!
  • Agustin Meriles
    Agustin Meriles about 5 years
    Currently, create-react-app is showing a deprecated warning if you use this approach. The recommended way is now to use a jsConfig.json file: { "compilerOptions": { "baseUrl": "src" } }
  • Chasen Bettinger
    Chasen Bettinger almost 5 years
    More information about Agustin's comment found here: facebook.github.io/create-react-app/docs/…
  • Con Antonakos
    Con Antonakos over 4 years
    Two questions: (1) I'm having a hard time importing a folder with index.js. It won't implicitly understand to point to index.js to find the exports. (2) Can we customize the alias of the absolute import?
  • Zach Smith
    Zach Smith over 4 years
    think of the unfortunate new developer who starts working on your code base and has to deal with the ambiguity of npm packages vs folder names!!
  • Ben Smith
    Ben Smith over 3 years
    Cheers for the reference and +1 for getting eslint to work nicely with the solution.
  • Vigneshwaran Chandrasekaran
    Vigneshwaran Chandrasekaran over 3 years
  • Ben Smith
    Ben Smith over 3 years
    @VigneshwaranChandrasekaran that link is already included in my answer. See "...way to set absolute paths as documented here."
  • dmitri
    dmitri about 3 years
    that option is depricated and should not be used...
  • puerile
    puerile over 2 years
    I like this solution better. 👍