Introduction
Today, I want to show you the way to avoid these ugly paths on your typescript projects.
To something more readable, maintainable and fancier:
Path mapping
On Typescript project, we can use path mapping method through ts-config.json...
But, what does it mean โpath mappingโ on a Typescript project?
My ts-config.json
would look like this:
{
"compilerOptions": {
"baseUrl": "src", // This must be specified if "paths" is.
"paths": {
"@/components/*": ["components/*"]
}
}
}
The values inside paths
property tell the transpiler: for any module import that matches the patternย "@/components/*"
ย (*
i.e. all values), to look in location "components/*"
.
So now with these instructions in my .tsx file, if I import a new component :
import Button from "@/components/Button";
When I compile, the transpiler knows where is this component in my project because during the build process the transpiler combines the baseUrl
with components/*
:
<baseUrl>/components/Button
You can see the Typescript documentation for information about this: TypeScript: Documentation - Module Resolution (typescriptlang.org)
tsconfig-paths
If for some reason, you are working with node.js or some environment that doesn't use a module bundler like webpack or parcel you will additionally need tsconfig-paths package.
This package will read theย paths
ย fromย tsconfig.json
ย and convert node's module loading calls into physical file paths that node can load.
To do this, you need to preload tsconfig-paths/register
in your node command :
node -r tsconfig-paths/register main.js
Jest
Jest is a little mischievous with paths-mapping of Typescript, you need to specify the module mapping to him. For example in your jest.config.js
, you can set moduleNameMapper
property:
module.exports = {
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1"
},
}
Conclusion
I hope you were enjoyed reading this article. Itโs my first time, be indulgent with me please :D Also, I learn English, so donโt hesitate to notify me if I did mistakes.
You can follow me on my Github and my Portfolio (itโs under construction, but soon I will present it through a new article)
Top comments (2)
Good practice when you divide the imports in your code into those imported from
node_modules
and those imported from your local files.Thanks for your tip!