Solving Import Path Hell in Create React App: Aliases with CRACO or react-app-rewired
- Published on
- • 1 mins read•--- views
It is very important to have consistent import statements in your react projects, and to preserve relative paths hell, ex. ../../../utils/smth.ts looks much more ugly than ~/utils/smth.ts.
Unfortunately, latest versions of typescript support this trick worse and worse (I don't know why, in fact).
Using @craco/craco package
Steps for installation:
yarn add @craco/cracoMake file
craco.config.jsin root of projectPut text below to
craco.config.js:const path = require('path'); module.exports = { webpack: { alias: { '~': path.resolve(__dirname, 'src'), }, }, };Change react scripts in
package.jsonto:"scripts": { "start": "craco start", "build": "craco build", "test": "craco test", "eject": "craco eject" }Start project and check everything works:
yarn start
Using react-app-rewired and customize-cra
Steps for installation:
yarn add react-app-rewiredyarn add customize-craIn
config-overrides.jsadd those lines:const { addWebpackAlias } = require('customize-cra'); const path = require('path'); //... in module.export of configuration section: addWebpackAlias({ '~': path.resolve(__dirname, './src'), // ... });And font forget to add similar aliases to
tsconfig.json:"paths": { "~/*": [ "./src/*" ], },
Table of Contents
Open for contract collaboration
I am available for contract-based collaboration. If you have an interesting project idea, schedule a call via Calendly.
Schedule a 30-min call