Aliases in React app
Hi LinkedIn once again :)
this time I want to share something that will make your code better!
we all know about such imports
import componentA from '../../../components/componentA'
import componentB from '../../../components/componentB'
import {} from '../../services'
import {} from '../../../types''
with typescript, you can make it easier to import and even better, for example,
import { componentA, componentB } from '@/components'
import { authService, usersService } from '@/services'
import { IUser, ... } from '@/types'
this is called an alias and it actually easy to set up.
now, it depends on your application structure, for example in my starter project I built react-starter I added that line in tsconfig.json
"paths":
"@/*": ["./src/app/*"],
},
The "@" pointer to the application root folder (you can configure to any path)
do note that "baseUrl" is required, in most cases, you might already have it, if not just add "baseUrl": "."
Recommended by LinkedIn
And now you can easily import using that symbol you just set.
@/components = src/app/components ..etc
Now when you will try to run the project after this setup, you will run into an error that says it cannot find such a module, and that's true because when we compile our typescript files he has no idea what is @ symbol means, so in order to tell him that without eject the webpack configuration we can install a package called @craco/craco
this package helps us set a configuration to webpack without the need to eject the project in react app.
and then we need to use it at the package.json we need to replace the "scripts" to use craco:
"scripts":
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "craco eject"
},
and then at the root project add the craco.config.js with the following configuration:
const path = require('path')
module.exports = {
webpack: {
alias: {
'@': path.resolve(__dirname, 'src/app'),
},
},
})
And that's it! you got your Alias working in react app.
BTW, in Angular and Vue(vite) it is already setup, you don't need to install anything :)