1 of MANY ways to absolute path setup in Create React App

Alexander Lee
2 min readSep 14, 2017

--

I know I know, there are way too many articles regarding this. I myself went on google to trying to figure out how to add absolute path functionality so I can go from

import MyButton from ../../components/Button/MyButton.jsx

to

import Button from 'components/Button/MyButton.jsx'

As I was researching I realized OMG there are way too many ways to do this. The frustration was so REAL.

There were some solutions that worked based on the comments in the github issues but I realized some vital steps were missing. Without further ado this is the quick and easy way to setup proper aliasing.

  1. Create a project via create-react-app
  2. npm run eject to eject the application
  3. Go into both your config/webpack.config.dev.js and config/webpack.prod.js file
  4. Add the following in your alias object
alias: {
'components': path.resolve('src/components'), // This is ours!!
'react-native': 'react-native-web'
},

5. At this point you should create a components folder under src and test if it works properly. (Example setup below)

# App.js
import React, { Component } from 'react';
import Button from 'components/Button';

Side note:

Like all good applications you need tests. To get the imports working properly in that case… you can add the following to your package.json below your moduleFileExtensionskey.

{
....
"moduleFileExtensions": [ ....]
"moduleDirectories": ["node_modules", "src"] // This is ours!!
},
"babel": {
...
}

Conclusion

This was a fairly short article but that was super intentional. I spent a bit of time trying to figure this out because I ended up going through too many rabbit holes. Hope this helps save you from relative path hell! If you have any questions let me know.

--

--