Typescript paths with ts-node, ts-node-dev, and jest
Setting up TypeScript paths
Motivation
Working with large TypeScript codebases often leads to importing a lot of stuff from other modules via relative paths. Imagine something like the following:
While this isn’t a severe problem in smaller projects, navigating through a jungle of relative paths can get quite annoying over time. A better way to import something from another module could look something like this:
You get the idea.
TypeScript paths
Luckily, TypeScript provides us with a paths-option in the tsconfig.json. Imagine the following project structure:
To achieve the non-relative import mentioned above, tsconfig.json could look like this:
From the TypeScript docs:
baseUrl: Specify the base directory to resolve non-relative module names.
paths: Specify a set of entries that re-map imports to additional lookup locations.
So baseUrl specifies the base directory on which paths re-maps your imports.
ts-node and ts-node-dev
When starting your application via ts-node or ts-node-dev, you will get the following error:
Cannot find module ‘@utils/file-with-stuff-i-need’
Long story short, ts-node and ts-node-dev can not resolve imports according to baseUrl and paths (ts-node docs). To solve this problem we will use tsconfig-paths, a package that takes the baseUrl and paths options and does exactly what we want: resolving our re-mapped paths.
Install the package anyway you like:
yarn add — dev tsconfig-paths
Now we need to tell ts-node and ts-node-dev to use the tsconfig-paths package. In our example, we will change our package.json scripts from:
to:
Your application should now work as expected, and the @utils-paths resolve properly.
Jest
When running your tests you will again notice that something is going wrong: Jest also can not resolve your re-mapped paths automatically — even if you’re already using ts-jest.
For more information about using jest with TypeScript, take a look at the ts-jest documentation.
A basis ts-jest configuration looks like this:
To tell Jest to re-map our imports we will use the pathsToModuleNameMapper from ts-jest/utils:
Note that you don’t need tsconfig-paths for Jest. For more information take a look at https://kulshekhar.github.io/ts-jest/docs/getting-started/paths-mapping.
See you in the next one!