How I simplified my import paths in TypeScript
Andy Coupe
Posted on July 17, 2020
I think as developers using ES modules we have all got to a point where import paths start to become ugly and unmaintainable - especially in large codebases.
With a couple of lines added to your tsconfig.json
we can fix this.
Let's imagine we are importing a button into a file which is nested far away from the components directory.
import Button from '../../../components/button'
This doesn't look too bad but it can get quite annoying if you're having to do this regularly.
Jump over to your tsconfig.json
and reach into your tool belt.
We can add a paths
property to our tsconfig.json
. By doing this we also need to add a baseUrl
which our paths will use as a base.
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"@components/*": ["components/*"]
}
}
}
Now we can use these paths in our application. @components
will now map to src/components/*
.
So our button import from before can now be used like so.
import Button from '@components/button'
It doesn't look like much but in a monorepo this improves your workflow and efficiency as a developer.
A short but hopefully helpful post for some importers out there.
Posted on July 17, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.