Perhaps you’ve checked someone else’s project for inspiration and wondered why their import statements look different to yours?
// Yours
import { Button } from "../../../components/button";
// Theirs
import { Button } from "@/components/button";
import { Button } from "~/components/button";
The answer is most likely TypeScript path aliases also called import aliases.
Setting up path aliases in TS Config fileSection titled Setting%20up%20path%20aliases%20in%20TS%20Config%20file
The first step will be to change your tsconfig.json
file to add the following snippet.
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}
- Add a
baseUrl
andpaths
to yourcompilerOptions
. - The Base URL sets a base directory from which TypeScript will look for files starting at the same folder as the base URL. In most cases it will be the current directory of your app which is marked with a period/full stop.
- Paths re-maps import paths to lookup locations for your imports relative to the base URL.
Note: You can customise your import paths to whatever you need or like. You can use the @
symbol or ~
tilde, its your personal preference. You can even go to more specific paths in your project like a components folder. See the example below:
You can setup multiple paths to different locations in your project structureSection titled You%20can%20setup%20multiple%20paths%20to%20different%20locations%20in%20your%20project%20structure
In this example we’ve added 2 other import aliases that go to the components
folder and the lib
folder directly. This is useful for frequently imported modules.
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@components/*": ["src/components/*"],
"@lib/*": ["src/lib/*"]
}
}
}
// Example usage
import { myUtility } from "@lib/utils";