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/craco
-
Make file
craco.config.js
in root of project -
Put text below to
craco.config.js
:12345678const path = require('path');module.exports = {webpack: {alias: {'~': path.resolve(__dirname, 'src'),},},}; -
Change react scripts in
package.json
to:123456"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-rewired
-
yarn add customize-cra
-
In
config-overrides.js
add those lines:12345678const { 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
:12345"paths": {"~/*": ["./src/*"],},