In this article, I’ll be showing you how to enable absolute path imports in a create-react-app application without ejecting.
To enable absolute path imports, you just have to configure the baseUrl of your project’s jsconfig.json file. (tsconfig.json if you are using typescript)
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
If you currently have your application running, you’ll have to restart it to be able to start importing using absolute paths.
// Relative path import
import ComponentA from '../../components/ComponentA';
// Absolute path import
import ComponentA from 'components/ComponentA';
ESLint
If you are using ESLint, you might see some warnings that says Unable to resolve path to module ...
. You have to add the following ESLint configurations to your .eslintrc file, or inside your package.json file. In this example, I will be using the .eslintrc file.
{
"settings": {
"import/resolver": {
"node": {
"paths": ["src"]
}
}
}
}
I would like to add you can also custom aliases to jsconfig.json:
“compilerOptions”: {
“jsx”: “react”,
“baseUrl”: “.”,
“paths”: {
“stories/*”: [“./stories/*”],
“shared/*”: [“./src/shared/*”],
},
}
so you don’t have to write a long path all the time, and it’s more obvious what is consumed without caring where is it exactly