TypeScript aliases to help clean up import statements
Feb 20, 2021As a TypeScript project grows, you might get tired of your imports looking like this:
import {Button, Select, TextField} from '../../../../../../../../components';
import {useHistory} from '../../../../../../../../hooks';
import {getCacheValue} from '../../../../../../../../utilities';`
When it comes time to move this file to another directory, you might end up with broken imports wondering if you should import from '../../../../components'
or '../../../../../../components'
. This can cause a frustrating delay as you count up the folders between your current file and the one you are importing.
Fortunately there is an easy way to clean up these top level imports with a small change in your tsconfig.json
file. The baseUrl
compiler option allows you to set a base directory, relative to your tsconfig.json
file, for resolving non-relative modules.
In our example, the components
, hooks
, and utilities
folders are all at the same level as our tsconfig.json
file. By adding the line below to our config file, we can now import directly from these folders anywhere in our project.
{
"compilerOptions": {
"other": "options",
"baseUrl": "./"
},
"include": ["**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
import {Button, Select, TextField} from 'components';
import {useHistory} from 'hooks';
import {getCacheValue} from 'utilities';`
The baseUrl
option is documented here. If you need to get more specific for different modules, you can combine baseUrl
with paths
, documented here.