Solution for 2021.
Note: CRA. Initially the idea of using a third party library or ejecting app for alias seemed crazy to me. However, after 8 hours of searching (and trying variant with eject), it turned out that this option is the least painful.
Step 1.
yarn add --dev react-app-rewired react-app-rewire-alias
Step 2.
Create config-overrides.js file in your project's root and fill it with:
const {alias} = require('react-app-rewire-alias')
module.exports = function override(config) {
return alias({
assets: './src/assets',
'@components': './src/components',
})(config)
}
Step 3. Fix your package.json file:
"scripts": {
- "start": "react-scripts start",
+ "start": "react-app-rewired start",
- "build": "react-scripts build",
+ "build": "react-app-rewired build",
- "test": "react-scripts test",
+ "test": "react-app-rewired test",
"eject": "react-scripts eject"
}
If @declarations don't work, add them to the d.ts file.
For example:
'@constants': './src/constants'
, => add in react-app-env.d.ts declare module '@constants';
That is all. Now you can continue to use yarn or npm start/build/test commands as usual.
Full version in documentation.
Note: The Using with TypeScript / JavaScript configuration part in docs did not work for me. The error "aliased imports are not supported" when building the project remained. So I used an easier way. Luckily it works.