Setting up Path Alias in TypeScript and tsc build without error
Having hard time typing ../../../../ ?
When using TypeScript, there are an option for developers to easily import their modules without typing so many ../../../ or absolute path. And it is called Paths Alias.
This is how I setup path alias for my projects
First, install the following packages
yarn add -D tsconfig-paths tscpaths
// or
npm install --dev tsconfig-paths tscpaths
Second, go to your package.json and add the following codes to the script tag
{
"scripts": {
"start": "node -r tsconfig-paths/register -r ts-node
./src/index/ts",
"build": "tsc --project tsconfig.json && tscpaths -p
tsconfig.json -s ./src -o ./dist"
}
}
Third, go to tsconfig.json and add the paths alias options inside compilerOptions.
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": ["node_modules/*"],
"@youNameIt/*": ["path/to/your/module"]
}
}
}
Please be reminded that all paths in Paths are related to baseUrl, for example the complete path of @yourNameIt/* is ./path/to/your/module. so you don’t have to add ./ to your paths.
Tsc does not convert or map the paths alias for you.
when you try using
tsc
It successfully compile to js, but if you run the js file, you will find the error of @youNameIt/blah is not found something like that. This is because js does not understand what path alias is.
Therefore, you need tscpaths for production build.
What it does is to look for your source file (.ts) and find the relative path to each module you set as path alias, and go to your compiled js file and directly change the path from @youNameIt/blah to something like ../../you/name/it/blah.
I hope this article helps you.