Absolute paths with Create React App + Typescript (without ejecting)

Gustavo Graeff
2 min readAug 26, 2020

Hello Medium, this is my first story!

What do you feel while viewing this image?

Yes, it’s not great having countless “../ “ to import files within our projects.

I had problems creating an alias in Create React App + Typescript this week, and that’s why I’m here writing this!

Searching on the internet I saw some possible solutions after a few hours, mixing the possibilities I came up with the solution as you can see below:

You can solve it using 5 simple steps:

Step 1: Adding react-app-rewired into your devDependencies

yarn add -D react-app-rewired or npm install react-app-rewired — save-dev

Step 2: After installing, you’ll be able to change package.json default ReactJS scripts to:

“scripts”: { 
“start”: “react-app-rewired start”,
“build”: “react-app-rewired build”,
“test”: “react-app-rewired test”,
“eject”: “react-app-rewired eject”
}

Step 3: Creates a new file called tsconfig.paths.json on root path, with content like:

{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"services/*": ["./src/shared/services/*"],
"interfaces/*": ["./src/shared/interfaces/*"]
}
}
}

Tip 1: you can choose which path you want to use, like:
@services, @interface, @src, ~, @, etc just by changing the keys inside ”paths”: {}

The same is applied to it’s value: [“./src/shared/services/*”], [“./src/shared/interfaces/*”], [“./src/*”], use the relative path here.

Step 4: Into tsconfig.json, before ”compilerOptions” you need to extend the tsconfig.paths.json you just created.

Like this:

{
"extends": "./tsconfig.paths.json",
...//rest of file infos compilerOptions, include... whatever
}

Step 5: Creates a new file config-overrides.js, adding your alias and relative paths on it:

const path = require('path');module.exports = function override(config) {
config.resolve = {
...config.resolve,
alias: {
...config.alias,
'services': path.resolve(__dirname, 'src/shared/services'),
'interfaces': path.resolve(__dirname, 'src/shared/interfaces')
},
};
return config;
};

Tip 2: If you’re using eslint, remember to have a .eslintignore file and add config-overrides.js within it.

Restart your IDE or text editor, in my case VSCode.

It’s DONE! Now just run yarn start or npm run start and…

If you’ve questions or suggestions, please let me know in the comments below.

Repository which I came up with this solution: https://github.com/gustavograeff/study-project-1-frontend-react

--

--