React import root path helper

The thing you are asking is called "absolute import". "create react app" already provides a standard solution and recommends creating a jsconfig.json file in your root directory of react project.

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

Later you can import components as such:

import Button from 'components/Button';

Go to this link of official docs related to importing component and there u will find absolute import section:

https://create-react-app.dev/docs/importing-a-component/

And Yes don't forget to restart your react server after doing the changes : )


I was experiencing a similar problem. I finally resolved it by following this article: https://medium.com/@ktruong008/absolute-imports-with-create-react-app-4338fbca7e3d

  1. Create a .env file in the root of the react app
  2. Add a line NODE_PATH = src/

That worked for me.


It depends on your module bundler. For Webpack 2 you can do something like this:

module.exports = {
    ...

    resolve: {
        modules: [
            'node_modules',
            path.resolve(__dirname + '/src')
        ],
        alias: {
            src: path.resolve(__dirname + '/src')
        }
    },

    ...
}

the same for Webpack 1:

module.exports = {
    ...

    resolve: {
        root: [
            path.resolve(__dirname  + '/src')
        ],
        alias: {
            src: path.resolve(__dirname  + '/src')
        }
    },

    ...
}

Than you will be able to use src as a native path like this:

import approxPerDay from 'src/utils/approxPerDay.js'
import otherstuff from '../components/otherstuff'