how to setup an absolute path in a React TypeScript project
pwn0x80
Posted on June 22, 2023
To set up absolute paths in a React project you can follow these steps:
Install the required dependencies:
npx create-react-app my-app --template typescript
npm i cargo
Configure absolute paths:
make change on tsjsconfig.json and create carco.config.js file in the root directory of your React project with the following content:
tsjsconfig.json
configuring the baseUrl and paths in your tsconfig.json.
The base directory for resolving module paths is the src directory, as the "baseUrl" is set to "src".
Aliases for module paths are specified in the "paths" section. We've defined two aliases here:
"@components/": This alias corresponds to the path./components/. For instance, the resolution of "@components/Button" would be "./components/Button".
The alias "@utils/" corresponds to the./utils/ path.For instance, the resolution of "@utils/helpers" would be "./utils/helpers".
Make sure to modify the paths and aliases in accordance with the organisation of your project.
{
"compilerOptions":{
"baseUrl":"src",
"paths":{
//add paths line
"@components/*":[
"./components/*"
],
"@utils/*":[
"utils/*"
]
},
"target":"es5",
"lib":[
"dom",
"dom.iterable",
"esnext"
],
"allowJs":true,
"skipLibCheck":true,
"esModuleInterop":true,
"allowSyntheticDefaultImports":true,
"strict":true,
"forceConsistentCasingInFileNames":true,
"noFallthroughCasesInSwitch":true,
"module":"esnext",
"moduleResolution":"node",
"resolveJsonModule":true,
"isolatedModules":true,
"noEmit":true,
"jsx":"react-jsx"
},
"include":[
"src"
]
}
caraco.config.js
The tsConfigPath property is set to "./tsconfig.json", indicating the file path where the TypeScript configuration (tsconfig.json) is located.
This file contains the "baseUrl" and "paths" configurations for alias resolution.
const CracoAlias = require("craco-alias");
module.exports = {
plugins: [
{
plugin: CracoAlias,
options: {
source: "tsconfig",
// baseUrl SHOULD be specified
// plugin does not take it from tsconfig
baseUrl: "./src",
// tsConfigPath should point to the file where "baseUrl" and "paths" are specified
tsConfigPath: "./tsconfig.json"
}
}
]
};
Posted on June 22, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.