TLDR,
First you need to create React application 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
You'll also need craco-alias to resolve the alias paths
$ npm i craco
$ npm i -D craco-alias
#Or
$ yarn add craco
$ yarn add -D craco-alias
Create a file named craco.config.js and add the following code.
const CracoAlias = require("craco-alias");
module.exports = {
plugins: [
{
plugin: CracoAlias,
options: {
source: "tsconfig",
baseUrl: "./src",
tsConfigPath: "./tsconfig.paths.json",
},
},
],
};
Create a new file namedtsconfig.paths.json and add the following
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@components/*": ["./components/*"],
"@pages/*": ["./pages/*"],
"@api/*": ["./api/*"],
"@base/*": ["./*"]
}
}
}
Then in your tsconfig.json add this line
{
"compilerOptions": {
...
},
"extends": "./tsconfig.paths.json",
"include": ["src"]
}
My 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 using 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


Top comments (0)