Setting up a React project can be a fun exercise until you decide to move things around and noticed that all of local imports are broken. To avoid that, you can use absolute paths for imports.

NODE_PATH is a special environment variable that instructs Webpack to resolve from this folder. Assuming a project containing two folders in the src , containers and components the difference would look like:

Current Code

1
2
import { Header } from '../../components/Header'
import { FancyContainer } from '../FancyContainer'

New Code

1
2
import { Header } from 'components/Header'
import { FancyContainer } from 'containers/FancyContainer'

With the new structure, we can safely move our files around without worrying about where we are in the directory stack. To achieve this, we create a .env file in the root of our directory with NODE_PATH set to src

1
NODE_PATH=src

Next time we run the start command, it will pick up the path automatically 🎉