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

Image for post
Image for post

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.

Image for post
Image for post

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';
Image for post
Image for post

Side note:

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

Conclusion

Written by

Developer - tech/js/blockchain

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store