How to use module alias in React js (`CRA`)
Orinda Felix Ochieng
Posted on March 26, 2022
TLDR,
First you need to create React applicatin using Create React App (CRA)
$ npx create-react-app testing-alias --template typescript
# Or
$ yarn create react-app testing-alias --template typescript
Next Well add an override to the default webpack
We'll use craco
to run our application instead of react-scripts
$ npm i craco
#Or
$ yarn add craco
Once craco is installed, Create a craco.cofig.js
Then install tsconfig-paths-webpack-plugin
for loading the typescript paths
$ yarn add tsconfig-paths-webpack-plugin
#Or
$ npm i tsconfig-paths-webpack-plugin
Add the folling to your craco.config.js
const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin");
module.exports = {
webpack: {
plugins: [new TsconfigPathsPlugin()],
},
};
Add the following to your tsconfig.json
{
"compilerOptions":{
"baseUrl": "./src",
"paths": {
"@component/*": ["./src/@components/*"],
"@pages/*": ["./src/@pages/*"],
"@utils/*": ["./src/@utils/*"],
"@hooks/*": ["./src/@hooks/*"],
"@app:state/*": ["./src/state/*"]
}
},
"include": ["src"]
}
Then in your tsconfig.json
add the following to match our directory structure
Finally modify your package.json
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "react-scripts eject"
}
In the App.{js|ts}
you import the given component and the run your application using yarn start
or npm start
In conclusion we've learnt to add module aliasing to our react js packages ging absolute imports. It's easier this way given the growth of your application may have and also having similar names in either pages or components conflict is avoided. It's easier this way since you don't need to eject
your react app
Thanks to reading
Posted on March 26, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.